简体   繁体   English

如何对 R 中的一列求和,该列被另一列的值过滤? 还是到特定的行?

[英]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.

相关问题 根据R中同一行的另一列中的单元格的值对一列求和 - Sum a column based on the value of a cell in another column of the same row in R R-如何将某一列中特定事件的总和添加到另一列中 - R - How to add the sum of a specific occurrence in one column to another column 如何计算 R 中特定列的总和并将结果放在另一列中 - How to calculate the sum of specific columns in R and make the results in a another column R Dataframe:如何根据另一列中的相应值乘以一列中的过滤值? - R Dataframe: How to multiply filtered values in a column based on the corresponding value in another column? 如何计算R中具有不同行值的列中2个单元格的总和 - how to calculate the sum of 2 cells in a column with a different row value in R R:如果另一列中的行缺少值,如何提取列中的值名称和另一列的列名 - R: How to extract value name in a column and column name of another column if the row in the other column has a missing value 如何通过行/列名将矩阵单元格值相加到另一个? - How to sum a matrix cell value into another by row/column names? "根据 R 中另一列的条件求和(或不求和)一个值" - Sum (or not) a value based on condition of another column in R 将不同的列值行求和到R中的新列行 - sum different column value rows into a new column row in R 如何仅计算R中特定行的列值 - How to count only specific row's column value in R
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM