简体   繁体   中英

Combine values of data.frame

I'm R-beginner, I assume this is not so difficult. I want to combine values of a data.frame , like this:

Input data.frame:

  col1 col2
1 a   50
2 a   80
3 b   40
4 c   20 

Output data.frame:

 col1 col1
1 a [50,80]
2 b [40]
3 c [20]

In the input, col1 is not unique. For each value in col1 , I want to combine all values in col2 in a vector. In the output, col1 is unique.

Can you help me with this?

Entries of a data-frame cannot be lists, they must be atomic. What you probably want is to get a named list of vectors:

df <- data.frame( col1 = c('a','a','b','c'), col2 = c(50,80,40,20))
with(df, tapply(col2, col1, list))

which is a named list:

$a
[1] 50 80

$b
[1] 40

$c
[1] 20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM