【问题标题】:Producing a list from a data frame R从数据框 R 生成列表
【发布时间】:2018-07-05 14:30:54
【问题描述】:

我有一个包含姓氏和姓名的 2xN 矩阵,并且想要一个列表,其中键是姓氏,元素是姓氏的人。我可以使用 for 循环和附加代码来做到这一点,但想知道是否有 reshape 函数或直接执行此操作的东西。

people<-cbind.data.frame(c(rep("smith",2),rep("miller",2)),c("John","Jane","Alex","Jes"))

我想要一个x[["smith"]] 的列表

【问题讨论】:

    标签: r reshape reshape2


    【解决方案1】:

    你试过split()吗?

    split(people[[2]], people[[1]])
    $`miller`
    [1] Alex Jes 
    Levels: Alex Jane Jes John
    
    $smith
    [1] John Jane
    Levels: Alex Jane Jes John
    

    【讨论】:

      【解决方案2】:

      我知道你要求list,但对于 R 中的字典,我可以推荐hashmap

      people <-cbind.data.frame(c(rep("smith",2),rep("miller",2)),c("John","Jane","Alex","Jes"), stringsAsFactors=F)
      H      <- hashmap(people[,1], people[,2])
      H
      
      ## (character) => (character)
      ##    [miller] => [Jes]      
      ##     [smith] => [Jane]
      
      H$values()
      
      [1] "Jes"  "Jane"
      
      H$keys()
      
      [1] "miller" "smith"
      

      它非常高效,拥有令人难以置信的工具集,并为 R 提供了缺少的字典功能,然后还有一些!

      可以通过将查找键向量传递给 [[ 或 $find:

      H[["smi"]]
      
      H$find("mill")
      

      更多信息:

      https://github.com/nathan-russell/hashmap

      【讨论】:

      • 一定要去看看,谢谢提示!
      猜你喜欢
      • 1970-01-01
      • 2021-05-31
      • 2018-10-29
      • 1970-01-01
      • 2020-06-14
      • 1970-01-01
      • 2022-01-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多