Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/64.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 - Fatal编程技术网

R 基于公共值对两个数据帧求和

R 基于公共值对两个数据帧求和,r,R,我有一个看起来像 day.of.week count 1 0 3 2 3 1 3 4 1 4 5 1 5 6 3 还有一个 day.of.week count 1 0 17 2 1 6 3 2 1 4 3 1 5

我有一个看起来像

    day.of.week count
1           0     3
2           3     1
3           4     1
4           5     1
5           6     3
还有一个

    day.of.week count
1           0    17
2           1     6
3           2     1
4           3     1
5           4     5
6           5     1
7           6    13
我想根据星期几将值从df1添加到df2。我想用ddply

total=ddply(merge(total, subtotal, all.x=TRUE,all.y=TRUE),
                   .(day.of.week), summarize, count=sum(count))
它几乎可以工作,但合并合并了具有共享值的行。例如,在上面的示例中,day.of.week=5。不是合并到两个记录,每个记录的计数为1,而是合并到一个记录的计数为1,所以我得到的总计数为1,而不是总计数为2

       day.of.week count
  1            0     3
  2            0    17
  3            1     6
  4            2     1
  5            3     1
  6            4     1
  7            4     5
  8            5     1
  9            6     3
  10           6    13

除了Ben建议您使用
merge
,您还可以简单地使用子集:

d1 <- read.table(textConnection("    day.of.week count
1           0     3
2           3     1
3           4     1
4           5     1
5           6     3"),sep="",header = TRUE)

d2 <- read.table(textConnection("    day.of.week count1
1           0    17
2           1     6
3           2     1
4           3     1
5           4     5
6           5     1
7           6    13"),sep = "",header = TRUE)

d2[match(d1[,1],d2[,1]),2] <- d2[match(d1[,1],d2[,1]),2] + d1[,2]
> d2
  day.of.week count1
1           0     20
2           1      6
3           2      1
4           3      2
5           4      6
6           5      2
7           6     16

d1不需要合并。你可以简单地做

ddply(rbind(d1, d2), .(day.of.week), summarize, sum_count = sum(count))

我假设两个数据帧都有相同的列名
day.of.week
count

尝试
by=“day.of.week”
而不是
all.x=TRUE
all.y=TRUE
。我太难了。谢谢