[英]How to sum a column in R filtered by the value of another column? Or to a specific row?
I want to find the column sum for a data set when another column is a specific value.当另一列是特定值时,我想找到数据集的列总和。 Below is a screen grab of my data, I want to sum the farmID for each iteration.
下面是我的数据的屏幕截图,我想对每次迭代的 farmID 求和。
My guess would be that the code is IF(iteration=x), sum(FarmID) but I don't know how to make that happen.我的猜测是代码是 IF(iteration=x), sum(FarmID) 但我不知道如何实现。
partial screenshot of data部分数据截图
An alternative would be to use library(dplyr)
functions.另一种方法是使用
library(dplyr)
函数。 For example you can sum the farm IDs by iteration as such:例如,您可以通过迭代对场 ID 求和,如下所示:
yourdata %>%
group_by(Iteration) %>%
summarise(Farm_ID_sum = sum(Farm ID))
An example:一个例子:
example <- data.frame(
"Iteration" = sample(1:5, 20, replace = TRUE),
"FarmID" = sample(1:500, 20, replace = TRUE)
)
example %>%
group_by(Iteration) %>%
summarise(Farm_ID_sum = sum(FarmID))
# Gives the output:
# A tibble: 5 x 2
Iteration Farm_ID_sum
<int> <int>
1 1 790
2 2 694
3 3 391
4 4 1588
5 5 1828
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.