2013-04-30 54 views
0

我想从数据框上的操作中排除单个列。当然,我可以复制数据框而不使用我想排除的列,但这似乎是一种解决方法。必须有一种更简单的方式来考虑我认为的子集。R:子集:除了一列使用整个数据框

所以这个示例代码应该显示我所要做的。

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

任何帮助将不胜感激。

回答

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

尝试

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

另一种方法是在%in%操作(这是很方便的,如果你想使用一些不同的命名列):

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