如何基于其他列的总和添加新列

时间:2016-12-22 19:34:46

标签: r

我试图获得所有伤害每行的总数,但下面的代码给了我所有行的总伤害

flights$Total.Injuries =  sum( flights$Total.Fatal.Injuries,
                           flights$Total.Minor.Injuries,
                           flights$Total.Serious.Injuries,na.rm = TRUE )

我在这里做错了什么?

3 个答案:

答案 0 :(得分:1)

尝试rowSums(flight, na.rm=T)

rowSums(cbind(flights$Total.Fatal.Injuries, flights$Total.Minor.Injuries, flights$Total.Serious.Injuries),na.rm=T)

答案 1 :(得分:1)

尝试:

flights$Total.Injuries <= rowSums(flights[ , c(x, y, z)], na.rm=TRUE)

,其中     x = Total.Fatal.Injuries的列号,     y = Total.Minor.Injuries的列号, 和     z = Total.Serious.Injuries的列号

答案 2 :(得分:1)

或另一个选项Reduce +

flights$Total.Inuries <- Reduce(`+`, flights)