I was wondering why Example 2 in the following doesn't work (and potential solutions of course :P)
test <- data.frame('a'=1:5,'b'=6:10)
#Example 1:
'$'(get('test'),'b')
#Example 2:
columnname = 'b'
'$'(get('test'),columnname)
I was wondering why Example 2 in the following doesn't work (and potential solutions of course :P)
test <- data.frame('a'=1:5,'b'=6:10)
#Example 1:
'$'(get('test'),'b')
#Example 2:
columnname = 'b'
'$'(get('test'),columnname)
BECAUSE $
DOES NOT EVALUATE ITS SECOND ARGUMENT. (I thought this fact was clearly stated in the help page but after reviewing it, I am not so sure I can make that claim.) The relevant sentence in the help page is:
The main difference is that $ does not allow computed indices, whereas [[ does.
As iTech suggests, a crucial difference between [[
and $
is that $
requires a character vector as its second argument, while [[
is able to accept a character vector or an object name to be evaluated. (Another difference is that $
only accepts recursive object for its first argument.)
In searching for the prior times this question has been addressed I discovered another solution that should only be used to learn the language and not for your coding strategies:
columnname = 'b'
do.call( '$', list(get('test'), columnname))
[1] 6 7 8 9 10
This does provide another mechanism for evaluating the second argument as well as the first, but it looks like tortured code to me. You should be gathering your items to be processed in a list and running through them with lapply
or sapply
using "[[" or "[" as appropriate arguments for FUN
.
Just change $
to [[
Here is an example:
'[['(get('test'),columnname)
The idea is by using $
R is expecting the index to be a direct value or a symbol that does not require evaluation i.e. not a variable