如何在R中根据一个条件对列进行求和

1,525 阅读1分钟

你可以使用以下基本语法在R中根据条件对列进行求和。

#sum values in column 3 where col1 is equal to 'A'
sum(df[which(df$col1=='A'), 3])

下面的例子展示了如何在以下数据框架中实际使用这种语法。

#create data frame
df <- data.frame(conference = c('East', 'East', 'East', 'West', 'West', 'East'),
                 team = c('A', 'A', 'A', 'B', 'B', 'C'),
                 points = c(11, 8, 10, 6, 6, 5),
                 rebounds = c(7, 7, 6, 9, 12, 8))

#view data frame
df

  conference team points rebounds
1       East    A     11        7
2       East    A      8        7
3       East    A     10        6
4       West    B      6        9
5       West    B      6       12
6       East    C      5        8

例1:根据一个条件求一列之和

下面的代码显示了如何找到团队等于'A'的行的积分列之和。

#sum values in column 3 (points column) where team is equal to 'A'
sum(df[which(df$team=='A'), 3])

[1] 29

下面的代码显示了如何找到积分大于9的行的篮板列之和。

#sum values in column 4 (rebounds column) where points is greater than 9
sum(df[which(df$points > 9), 4])

[1] 13

例2: 基于多个条件的一列之和

下面的代码显示了如何在球队等于 "A "和_会议_等于 "东部 "的行中找到得分列的总和。

#sum values in column 3 (points column) where team is 'A' and conference is 'East'
sum(df[which(df$team=='A' & df$conference=='East'), 3])

[1] 29

请注意,在R语言中,&操作符代表 "和"。

例3:根据几个条件中的一个条件求一列之和

下面的代码显示了如何找到球队等于 "A "或 "C_"的行的分数列之和。_

#sum values in column 3 (points column) where team is 'A' or 'C'
sum(df[which(df$team == 'A' | df$team =='C'), 3])

[1] 34

请注意,**|**操作符在R中代表 "或"。

其他资源

下面的教程解释了如何在R中执行其他常用函数。

如何在R中对特定列求和
如何在R中对特定行求和
如何在R中按组计算求和

The postHow to Sum Columns Based on a Condition in Rappeared first onStatology.