将两个数据框中的所有行成对求和并保存到矩阵
我有一个数据框 df1 和一个数据框 df 2
df1
colA colB ...
30 2 ...
3 100 ...
15 9 ...
.. .. ...
df2
colA colB ...
10 200 ...
0 10 ...
55 1 ...
.. .. ...
我想将 df1 的 colA 中的所有行与 df2 中的 colA 中的所有行相加,依此类推,对于其余列
输出:
df3
colA colB
40 202
3 110
70 10
我想将值填充到矩阵中 我写了这样的东西:
results <- matrix(NA, ncol=ncol(df1), nrow=nrow(df1))
rownames(results) <- rownames(df1)
colnames(results) <- colnames(df1)
for (i in seq(df1)) {
tempCol1 <- df1[, i]
for (row in rownames(results))
for (j in seq(results)){
results[row,j]<-sum(df1[row, tempCol1 ],
df2[row, tempCol1 ])
}}
它给出了这个错误:
[<-
(*tmp*
, row, j, value = sum(a[row, tempCol1], b[row, tempCol1])) : 下标越界
I have a data frame df1 and a data frame df 2
df1
colA colB ...
30 2 ...
3 100 ...
15 9 ...
.. .. ...
df2
colA colB ...
10 200 ...
0 10 ...
55 1 ...
.. .. ...
I would like to sum all the rows in colA of df1 with colA in df2 and so on for the rest of the columns
Output:
df3
colA colB
40 202
3 110
70 10
I would like to fill up the values to a matrix
I have written something like this:
results <- matrix(NA, ncol=ncol(df1), nrow=nrow(df1))
rownames(results) <- rownames(df1)
colnames(results) <- colnames(df1)
for (i in seq(df1)) {
tempCol1 <- df1[, i]
for (row in rownames(results))
for (j in seq(results)){
results[row,j]<-sum(df1[row, tempCol1 ],
df2[row, tempCol1 ])
}}
it give this error:
Error in
[<-
(*tmp*
, row, j, value = sum(a[row, tempCol1], b[row,
tempCol1])) : subscript out of bounds
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将其制成矩阵并将它们相加。
直接添加两个
data.frame
也可以。Make it to a matrix and add up them.
Directly add two
data.frame
also works as well.您不必使用
for 循环
来解决此问题。只需将它们相加即可:You do not have to use a
for loop
for this problem. Simply add them up:我们可以做一个常规的 + ,它将保留矩阵格式并进行元素求和,下面的代码片段将完成工作
We can do a regular + which will preserve the matrix format and does the elementwise summation, below snippet will get the job done