[R] Add function to each row excluding certain columns

David Winsemius dwinsemius at comcast.net
Thu Oct 10 00:52:29 CEST 2013

On Oct 9, 2013, at 3:31 PM, laro wrote:

> Thank you again! But somehow the which(function) didn't work...
> The problem is, that the columns I want to drop in further calculations will
> not have the same name, that's why I'm looking for a solution to make a
> vector of the columns that should be omitted, like
> omit<-c("Restriction 1","Restriction 2")
> and then simple add the function max to the rows, withour the listed columns
> in omit (I know this doesn't work, but something like this)
> example1New <- cbind(example1, `MAX without
> Restriction`=apply(example1[,-omit],1,max,na.rm=TRUE))

The "-" operator does not succeed in de-selecting named columns when using the"[" function:

Try instead:

example1New <- cbind(example1,
                     `MAX withoutRestriction` =
                          apply(example1[, ! names(example) %in% omit], 1, max,na.rm=TRUE))

The other alternative (to exclude all columns with "Restriction" in their names would be:

   ...(  example1[, -grep("Restriction", names(example) ) ]


   subset(example, select = -omit)

I think you should abandon the back-tick tricks you are using to preserve spaces in dataframe or matrix column names. I think they will cause problems for you in the future.

> Is there any way?
> Kind regards
> --
> View this message in context: http://r.789695.n4.nabble.com/Add-function-to-each-row-excluding-certain-columns-tp4677914p4677934.html
> Sent from the R help mailing list archive at Nabble.com.
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

David Winsemius
Alameda, CA, USA

More information about the R-help mailing list