【问题标题】:convert dataframe to list by row with named vectors in R [duplicate]使用R中的命名向量将数据帧转换为逐行列表[重复]
【发布时间】:2016-11-27 07:48:27
【问题描述】:

假设我有以下数据框:

  | a | b | c |
x | 1 | 2 | 3 |
y | 4 | 5 | 6 |
z | 7 | 8 | 9 |

我想将它逐行转换成一个列表,每个包含一个命名向量,基本上相当于list(x=c(a=1,b=2,c=3), y=c(a=4,b=5,c=6), x=c(a=7,b=8,c=9))的输出:

$x
a b c 
1 2 3 

$y
a b c 
4 5 6 

$x
a b c 
7 8 9 

我该怎么做呢?

【问题讨论】:

    标签: r


    【解决方案1】:

    我们可以使用

    res <- lapply(split(df1, row.names(df1)), unlist)
    str(res)
    #List of 3
    #$ x: Named int [1:3] 1 2 3
    #  ..- attr(*, "names")= chr [1:3] "a" "b" "c"
    #$ y: Named int [1:3] 4 5 6
    # ..- attr(*, "names")= chr [1:3] "a" "b" "c"
    #$ z: Named int [1:3] 7 8 9
    # ..- attr(*, "names")= chr [1:3] "a" "b" "c"
    

    【讨论】:

    • 谢谢!但结果不是命名向量列表,列表键只是数字而不是行名。
    • @Cenoc 我稍微更改了代码。你还认为它不是命名向量列表吗?
    【解决方案2】:

    我非常喜欢使用 purrr 包来完成这些任务:

    df <- read.table(text = "   a  b  c
                         x  1  2  3 
                         y  4  5  6 
                         z  7  8  9", header = TRUE)
    
    library(purrr)
    
    df_as_list <- set_names(by_row(df, ~ unlist(.x), .collate = "list")$.out, rownames(df))
    
    df_as_list  
    
    # $x
    # a b c 
    # 1 2 3 
    # 
    # $y
    # a b c 
    # 4 5 6 
    # 
    # $z
    # a b c 
    # 7 8 9 
    
    typeof(df_as_list$x)
    # [1] "integer"
    

    顾名思义,by_row 按行循环通过df,在这种情况下,将unlist(a_row) 应用于每一行,将其作为向量返回。因为我们希望将输出作为列表.collate 设置为"list"。我们返回列表.out,然后根据需要命名(因为名称不会自然保留)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-22
      • 2015-08-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多