[英]Summing columns from multiple data frames in R
I have multiple dataframes that I created in a for loop.我在 for 循环中创建了多个数据框。 They all have the same 3 columns, XLocs, YLocs, PatchStatus.它们都有相同的 3 列,XLocs、YLocs、PatchStatus。 XLocs and YLocs contain the same coordinates in each dataframe. XLocs 和 YLocs 在每个数据框中包含相同的坐标。 PatchStatus can be either 0 or 1 depending how the model ran. PatchStatus 可以是 0 或 1,具体取决于模型的运行方式。 Example of dataframe 1 looks like数据框 1 的示例看起来像
print(listofdfs[1])
allPoints.xLocs allPoints.yLocs allPoints.patchStatus
1 73.5289654 8.8633913 0
2 21.0795393 44.4840248 0
3 51.5969348 21.7864016 0
4 61.9007129 32.4763183 1
5 62.3447741 41.0651838 1
6 16.9311605 6.3765206 0
And dataframe 2 looks like数据框 2 看起来像
print(listofdfs[2])
allPoints.xLocs allPoints.yLocs allPoints.patchStatus
1 73.5289654 8.8633913 0
2 21.0795393 44.4840248 1
3 51.5969348 21.7864016 0
4 61.9007129 32.4763183 1
5 62.3447741 41.0651838 1
6 16.9311605 6.3765206 0
I'm hoping to have 1 resultant dataframe that has XLocs, YLocs, and SUM of patch status (note I plan on combining 15 data frames, so PatchStatus can be between 0 and 15).我希望有 1 个结果数据帧,其中包含 XLocs、YLocs 和补丁状态的 SUM(注意我计划组合 15 个数据帧,因此 PatchStatus 可以介于 0 和 15 之间)。
We can bind the datasets together and do a group by sum
我们可以将数据集绑定在一起并按sum
进行分组
library(dplyr)
bind_rows(listofdfs) %>%
group_by( allPoints.xLocs, allPoints.yLocs) %>%
summarise(allPoints.patchStatus = sum(allPoints.patchStatus))
Or using rbind
and aggregate
from base R
或者使用rbind
和来自base R
aggregate
aggregate(allPoints.patchStatus ~ ., do.call(rbind, listofdfs), FUN = sum)
I posted this answer along with the heatmap - Plot-3: https://stackoverflow.com/a/60974584/1691723我将此答案与热图一起发布 - Plot-3: https : //stackoverflow.com/a/60974584/1691723
library('data.table')
df2 <- rbindlist(l = listofdfs)
df2 <- df2[, .(sum_patch = sum(allPoints.patchStatus)), by = .(allPoints.xLocs, allPoints.yLocs)]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.