Dave
Dave

Reputation: 35

Adding multiple columns together based on condition

I want to add together a few columns of data, similar to this,

mtcars[,12] <- mtcars[2]+mtcars[4]+mtcars[6]

but I want to do it based on specific conditions. An example of a condition would be if the mean of one of the columns is greater than a certain number, similar to this

mtcars[,12] <- 
  ifelse(colMeans(mtcars[3])>=240,mtcars[2],0) +
  ifelse(colMeans(mtcars[3])>=230,mtcars[4],0) +
  ifelse(colMeans(mtcars[3])>=220,mtcars[6],0)

I get an error of: non-numeric argument to binary operator

How do I make this work?

Upvotes: 1

Views: 29

Answers (1)

akrun
akrun

Reputation: 887741

If there is a single column, we don't need colMeans

ifelse(rep(mean(mtcars[,3])>=240, nrow(mtcars)),mtcars[,2],0) +
     ifelse(rep(mean(mtcars[,3])>=230, nrow(mtcars)),mtcars[,4],0) +
     ifelse(rep(mean(mtcars[,3])>=220, nrow(mtcars)),mtcars[,6],0)
#[1] 112.620 112.875  95.320 113.215 178.440 108.460 248.570  65.190  98.150 126.440 126.440 184.070 183.730
#[14] 183.780 210.250 220.424 235.345  68.200  53.615  66.835  99.465 153.520 153.435 248.840 178.845  67.935
#[27]  93.140 114.513 267.170 177.770 338.570 111.780

Based on the condition showed, the input 'test' from mean or colMeans return a single value i.e. TRUE/FALSE, but the 'yes', 'no' are of different length i.e. mtcars[2]. If we need the whole column, either we replicate the arguments or use if/else

f1 <- function(dat, colind1, colind2, val) {
               if(mean(dat[[colind1]]) >= val) dat[[colind2]] else 0
  }
f1(mtcars, 3, 2, 240) + f1(mtcars, 3, 4, 230) + f1(mtcars, 3, 6, 220)
#[1] 112.620 112.875  95.320 113.215 178.440 108.460 248.570  65.190  98.150 126.440 126.440 184.070 183.730
#[14] 183.780 210.250 220.424 235.345  68.200  53.615  66.835  99.465 153.520 153.435 248.840 178.845  67.935
#[27]  93.140 114.513 267.170 177.770 338.570 111.780

Upvotes: 1

Related Questions