Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/78.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
合并重复的行并在R中添加列_R_Aggregate - Fatal编程技术网

合并重复的行并在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