qbert65536
qbert65536

Reputation: 459

How to add a new column based on summation of other columns

I'm trying to get the total number of all injuries per row, but the code below is giving me the total injuries for all rows

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

What am I doing wrong here ?

Upvotes: 0

Views: 2541

Answers (3)

akrun
akrun

Reputation: 886938

Or another option is Reduce with +

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

Upvotes: 1

Anthony Watson
Anthony Watson

Reputation: 108

Try:

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

where x = column number for Total.Fatal.Injuries, y = column number for Total.Minor.Injuries, and z = column number for Total.Serious.Injuries

Upvotes: 1

Bastien
Bastien

Reputation: 3087

Try rowSums(flight, na.rm=T),

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

Upvotes: 1

Related Questions