r - Indexing a dataframe with $ inside a function? -


many r textbooks encourage use of $ retrieve variables (columns) data.frames^. however, found not work inside function, , can't figure out why.

data(bod) print(bod)  # these work.  bod$'demand' bod[ ,'demand']  # works. myfunc1 <- function(x, y){   z <- x[ , y]   return(z) } out <- myfunc(bod, 'demand')  # doesn't work. myfunc2 <- function(x, y){   z <- x$y   return(z) } out <- myfunc2(bod, 'demand') 

i notice in r language definition says:

the form using $ applies recursive objects such lists , pairlists. allows literal >character string or symbol index. is, index not computable: cases >you need evaluate expression find index, use x[[expr]]. when $ applied >non-recursive object result used null: r 2.6.0 error.

is myfunc2 above example $ not being supplied literal character string?

^ zuur 2009 'beginner's guide r' p 61

^ spector 2008 'data manipulation r' p 26, 64, 69

you can use [[ instead of $

myfunc2 <- function(x, y){ +     z <- x[[y]] +     return(z) + } > myfunc2(bod, 'demand') [1]  8.3 10.3 19.0 16.0 15.6 19.8 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -