Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

r - Gather the values of one column based on another column of a dataframe and create list of named lists with them

I have the dataframe below:

name<-c("Jack","Bob","Jack","Bob")
item<-c("apple","olive","banana","tomato")
d<-data.frame(name,item)


name   item
1 Jack  apple
2  Bob  olive
3 Jack banana
4  Bob tomato

and I would like to create a list which will include as many lists as the unique values of name and each one will include the values of item that correspond to that name. The new list will be like:

words
[[1]]
[1] "apple"  "banana"

[[2]]
[1] "olive"  "tomato"

if instead of [[1]] and [[2]] I could have the actual values of name that correspond, [[Jack]] and [[Bob]] it would be good as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this creating a list with split() and then formating the data as you wish:

#Code
L1 <- split(d,d$name)
L1 <- lapply(L1,function(x) {x$name<-NULL;x})
L1 <- lapply(L1,function(x) {y<- x$item;y})

Output:

L1
$Bob
[1] "olive"  "tomato"

$Jack
[1] "apple"  "banana"

For sure you can use L1['Bob'] and so on to explore the list.

The fast way can be (Many thanks and credits to @mt1022):

#Code2
L <- split(d$item, d$name)

Output:

L
$Bob
[1] "olive"  "tomato"

$Jack
[1] "apple"  "banana"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...