How can I call matrix$col, inside a function? The matrix name is one of the variables of the function, while the column name I get by assuming that it should have a certain characters. something like this function(matrix){ colname=as.name(grep("[A-T a-t]ting",colnames(matrix),value=TRUE)) output=2*(matrix$colname) return(output) } The name of the column is Testing.
R. Michael Weylandt <michael.weylandt@gmail.com>
2011-Oct-07 15:09 UTC
[R] function - access column
Perhaps something like this: Test <- function(m){ m <- if(is.character(m)) get(m) else m stopifnot(length(colnames(m))>0) n = colnames(m) # Process n however 2* m[, n] } That make sense? Hope it helps, Michael On Oct 7, 2011, at 11:03 AM, Ana <rrasterr at gmail.com> wrote:> How can I call matrix$col, inside a function? > The matrix name is one of the variables of the function, while the > column name I get by assuming that it should have a certain > characters. > > something like this > > function(matrix){ > colname=as.name(grep("[A-T a-t]ting",colnames(matrix),value=TRUE)) > output=2*(matrix$colname) > return(output) > } > > The name of the column is Testing. > > ______________________________________________ > 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.
Thanks! It helps. I completely forgot about the colnames function I added a "which(colnames(m)==n)" to my own function and now I can access with no problem the column by the number instead of the name. On Fri, Oct 7, 2011 at 5:09 PM, R. Michael Weylandt <michael.weylandt at gmail.com> <michael.weylandt at gmail.com> wrote:> Perhaps something like this: > > Test <- function(m){ > ? ? m <- if(is.character(m)) get(m) else m > ? ? stopifnot(length(colnames(m))>0) > ? ? n = colnames(m) > ? ? # Process n however > ? ? 2* m[, n] > } > > That make sense? > > Hope it helps, > Michael > > > On Oct 7, 2011, at 11:03 AM, Ana <rrasterr at gmail.com> wrote: > >> How can I call matrix$col, inside a function? >> The matrix name is one of the variables of the function, while the >> column name I get by assuming that it should have a certain >> characters. >> >> something like this >> >> function(matrix){ >> colname=as.name(grep("[A-T a-t]ting",colnames(matrix),value=TRUE)) >> output=2*(matrix$colname) >> return(output) >> } >> >> The name of the column is Testing. >> >> ______________________________________________ >> 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. >