简体   繁体   English

根据 R 中另一列的值对列中的值进行分组

[英]Group values from a column based on another column's values in R

I have a dataframe and I would like all values in the second column to be stored together when they have the same value in the first column.我有一个 dataframe,我希望第二列中的所有值在第一列中具有相同值时存储在一起。 One of the difficulties is to put these values in quotation marks separated by semicolons only when there are several of them.困难之一是仅当有多个值时才将这些值放在引号中并用分号分隔。

A   12
A   56
A   23
B   16
C   04
C   73

The result would be this:结果是这样的:

A   "12;56;23"
B   16
C   "04;73"

I saw that the function fill() of tydir allows to do more or less the opposite of what I want, but I don't know any function able to do that.我看到 tydir 的 function fill() 允许做或多或少与我想要的相反的事情,但我不知道任何 function 能够做到这一点。 If you can give me some clues, Thanks !如果能给我一些线索,谢谢!

We can use paste with collapse after grouping我们可以在分组后使用paste with collapse

aggregate(col2 ~ col1, df1, \(x) 
    if(length(x) > 1) dQuote(paste(x, collapse =";"), FALSE) else x)

-output -输出

 col1       col2
1    A "12;56;23"
2    B         16
3    C     "4;73"

data数据

df1 <- structure(list(col1 = c("A", "A", "A", "B", "C", "C"), col2 = c(12L, 
56L, 23L, 16L, 4L, 73L)), class = "data.frame", row.names = c(NA, 
-6L))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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