合并重复的行并在R中添加列
我想知道如何在数据帧中合并重复的行,然后在另一列中合并重复的值 下面是一个现有数据帧的示例和两个可以作为解决方案接受的数据帧合并重复的行并在R中添加列,r,aggregate,R,Aggregate,我想知道如何在数据帧中合并重复的行,然后在另一列中合并重复的值 下面是一个现有数据帧的示例和两个可以作为解决方案接受的数据帧 df1 <- data.frame(col1 = c("test1", "test2", "test2", "test3"), col2 = c(1, 2, 3, 4)) df.ideal <- data.frame(col1 = c("test1", "test2", "test3"), col2 = c(1, "2, 3", 4)) df.ideal2 &
df1 <- data.frame(col1 = c("test1", "test2", "test2", "test3"), col2 = c(1, 2, 3, 4))
df.ideal <- data.frame(col1 = c("test1", "test2", "test3"), col2 = c(1, "2, 3", 4))
df.ideal2 <- data.frame(col1 = c("test1", "test2", "test3"),
col2 = c(1, 2, 4),
col3 = c(NA, 3, NA))
df1要从df1
转到df.ideal
,可以使用aggregate()
如果你想进入df.ideal2
,那更多的是一个从长到宽的重塑过程。你能行
reshape(transform(df1, time=ave(col2, col1, FUN=seq_along)), idvar="col1", direction="wide")
# col1 col2.1 col2.2
# 1 test1 1 NA
# 2 test2 2 3
# 4 test3 4 NA
仅使用基本的重塑()
函数。另一个选项是使用splitstackshape
library(data.table)
library(splitstackshape)
DT1 <- setDT(df1)[,list(col2=toString(col2)) ,col1]
DT1
# col1 col2
#1: test1 1
#2: test2 2, 3
#3: test3 4
或者从df1
dcast.data.table(getanID(df1, 'col1'), col1~.id, value.var='col2')
# col1 1 2
#1: test1 1 NA
#2: test2 2 3
#3: test3 4 NA
可能聚合(col2~col1、df1、toString)
会更干净
cSplit(DT1, 'col2', sep=',')
# col1 col2_1 col2_2
#1: test1 1 NA
#2: test2 2 3
#3: test3 4 NA
dcast.data.table(getanID(df1, 'col1'), col1~.id, value.var='col2')
# col1 1 2
#1: test1 1 NA
#2: test2 2 3
#3: test3 4 NA