R: 子集:使用整个数据框,除了一个列

3
我希望从一个数据框中排除一列进行操作。当然,我可以复制不包含想要排除的列的数据框,但这似乎是一个变通方法。我认为必须有一种更简单的子集方式。
所以,这个例子代码应该展示我正在做什么。
df<-data.frame(a=c(1:5),b=c(6:10),c=c(11:15))
# First subset: operate on a single column
mean(df[,1])
[1] 3
# Second subset: with a set of choosen columns
colMeans(df[,c(1,3)])
a  c 
3 13 
# third subset: exclude column b from the operation (expected Output should be like the second subset)
colMeans(df[,!=2])
Error: unexpected '!=' in "colMeans(df[,!="

任何帮助都将不胜感激。
3个回答

12
> colMeans(df[,-2])
 a  c 
 3 13 

10

另一个选择是使用%in%运算符(如果您想使用几个不同的命名列,这很方便):

colMeans( df[ , ! colnames(df) %in% c("b") ])
#a  c 
#3 13 

5

尝试

colMeans(df[, -2])
##  a  c 
##  3 13 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接