3

I'd like to exclude one single column from a operation on a dataframe. Of course I could just replicate the dataframe without the column that I want to exclude, but this seems to be a workaround. There must be an easier way to subset I think.

So this example code should show what I am up to.

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[,!="

Any help would be very appreciated.

4

3 回答 3

10

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

colMeans( df[ , ! colnames(df) %in% c("b") ])
#a  c 
#3 13 
于 2013-04-30T08:21:47.380 回答
10
> colMeans(df[,-2])
 a  c 
 3 13 
于 2013-04-30T07:59:37.757 回答
4

尝试

colMeans(df[, -2])
##  a  c 
##  3 13 
于 2013-04-30T08:00:12.077 回答