我想做的是在满足条件的情况下减去数据帧中的列。这不是我的数据,而是测试数据。
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
以下是我尝试使用的代码。我想要ncol =碳水化合物减去ncol -2还是ncol =齿轮ncol-1
w <- function(x){if (x[,ncol(x)] == c("carb")) {(ncol(x)-2)} else (ncol(x)-1)};
输出:
Warning message:
In if (x[, ncol(x)] == c("carb")) { :
the condition has length > 1 and only the first element will be used
我知道这是在谈论逻辑问题,但是我可以从这里弄清楚该做什么。
然后,我想将其吐入:(这是用于我的数据,并且未在上面的数据中复制)
Subtract<- finaltable[paste(tmp), w];
有人可以帮我这个忙吗?
根据评论,您需要使用以下任一方法:
names(x)[ncol(x)] # [1] "carb"
tail(names(x),1) # [1] "carb"
检查最后一列的名称。相对于:
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
...实际上将返回最后一列的内容,而不是列名。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句