R: Subset: Using whole dataframe except one column

16,804

Solution 1

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

Solution 2

An alternative would be the %in% operator (which is handy if you want to use a few different named columns):

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

Solution 3

Try

colMeans(df[, -2])
##  a  c 
##  3 13 
Share:
16,804
Joschi
Author by

Joschi

Updated on June 23, 2022

Comments

  • Joschi
    Joschi almost 2 years

    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.