Reputation: 149
What I want to do is subtract columns in data frame if condition is met. This isnt my data, but test data.
x<-mtcars;
x;
mpg cyl disp hp drat wt qsec vs am gear carb
Mazda RX4 42.0 12 320 220 7.80 5.24 32.92 0 2 8 8
Mazda RX4 Wag 42.0 12 320 220 7.80 5.75 34.04 0 2 8 8
Datsun 710 45.6 8 216 186 7.70 4.64 37.22 2 2 8 2
Hornet 4 Drive 42.8 12 516 220 6.16 6.43 38.88 2 0 6 2
Hornet Sportabout 37.4 16 720 350 6.30 6.88 34.04 0 0 6 4
Valiant 36.2 12 450 210 5.52 6.92 40.44 2 0 6 2
Below is the code I am trying to use. I want if ncol = carb subtract ncol -2 or if ncol = gear ncol - 1
w <- function(x){if (x[,ncol(x)] == c("carb")) {(ncol(x)-2)} else (ncol(x)-1)};
output:
Warning message:
In if (x[, ncol(x)] == c("carb")) { :
the condition has length > 1 and only the first element will be used
I get that the this is talking about logical things, but I can figure out what the heck to do from here.
I then want to spit this into: (this is for my data, and isnt replicated in data above)
Subtract<- finaltable[paste(tmp), w];
Can someone help me get this to work?
Upvotes: 0
Views: 426
Reputation: 93813
In light of the comments, you need to use one of either:
names(x)[ncol(x)] # [1] "carb"
tail(names(x),1) # [1] "carb"
to check against the last column name. As opposed to:
x[,ncol(x)]
#[1] 4 4 1 1 2 1 4 2 2 4 4 3 3 3 4 4 4 1 2 1 1 2 2 4 2 1 2 2 4 6 8 2
...which will actually return the contents of the last column rather than the column name.
Upvotes: 2