从数据框 R 生成列表

Producing a list from a data frame R

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

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

我想要一个列表,其中 x[["smith"]]

你试过了吗split()

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

$smith
[1] John Jane
Levels: Alex Jane Jes John

我知道你要 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