【问题标题】:Turn a col into rownames in a list of dataframes将列转换为数据框列表中的行名
【发布时间】:2020-05-29 10:45:52
【问题描述】:

我有一个数据框列表,我想将其中一个列转换为行名。 (而不是单独为每个 df 执行此操作)。

很遗憾我不能让它工作,也许有人可以帮忙?

DF1 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
DF2 <- data.frame(A = c("A", "B", "C"),
                  B = 1:3)
TheList <- list(DF1 = DF1,
                DF2 = DF2)
col_to_rownames_andDel <- function(df){
  rownames(df) <- df$A
  df$A <- NULL
}

TheList_namedRows <- map(TheList, col_to_rownames_andDel) #not working and empties the dfs

谢谢!

塞巴斯蒂安

【问题讨论】:

    标签: r list dplyr


    【解决方案1】:

    在函数的最后一行返回更改的数据框。

    col_to_rownames_andDel <- function(df){
       rownames(df) <- df$A
       df$A <- NULL
       return(df)
    }
    
    TheList_namedRows <- purrr::map(TheList, col_to_rownames_andDel)
    #Using lapply
    #TheList_namedRows <- lapply(TheList, col_to_rownames_andDel)
    
    TheList_namedRows
    #$DF1
    #  B
    #A 1
    #B 2
    #C 3
    
    #$DF2
    #  B
    #A 1
    #B 2
    #C 3
    

    【讨论】:

      【解决方案2】:

      嗯...似乎我只是忘记了函数中的返回参数。 它可能对其他人有用,所以我把它放在这里。

      col_to_rownames_andDel <- function(df){
        rownames(df) <- df$A
        df$A <- NULL
        return(df)
      }
      
      TheList_namedRows <- map(TheList, col_to_rownames_andDel)
      

      最好的橡皮鸭调试。

      【讨论】:

        【解决方案3】:

        你也可以这样做:

        map(.x = TheList,
            ~ .x %>%
            column_to_rownames("A"))
        
        $DF1
          B
        A 1
        B 2
        C 3
        
        $DF2
          B
        A 1
        B 2
        C 3
        

        【讨论】:

        • 我很欣赏它是一个 dplyr 解决方案,但 Ronak 更快。仍然非常感谢:)
        【解决方案4】:

        我们可以从tibble使用column_to_rownames

        library(tibble)
        library(purrr)
        map(TheList,  column_to_rownames, "A") 
        #$DF1
        #  B
        #A 1
        #B 2
        #C 3
        
        #$DF2
        #  B
        #A 1
        #B 2
        #C 3
        

        【讨论】:

          猜你喜欢
          • 2017-10-17
          • 1970-01-01
          • 1970-01-01
          • 2020-04-17
          相关资源
          最近更新 更多