I am trying to programmatically initialize some variables in R so that the variable name would be the evaluated content of the string.
Just this code:
library(dplyr)
v <- 'sum.of.ranfx'
new_v = sym(v)
!!new_v <- vector(mode = "list", length = 122)
fails with
Error in !`*tmp*` : invalid argument type
Google gives me no hits for this exact error. Here is an example accepted and upvoted SO answer whose syntax example I think I am following. Can you tell me what I'm doing wrong?
CodePudding user response:
You may use assign
-
v <- 'sum.of.ranfx'
assign(v, vector(mode = "list", length = 122))
CodePudding user response:
raw !! is not accepted, so you should put ` around the !!new to make it work
`!!new`= vector(mode = "list", length = 122)
I think it's because ! is used to 'reverse' a T
or a F
ex:
> !TRUE
[1] FALSE
> !!TRUE
[1] TRUE
So when you try to create a variable without specifying the ! should be used as a character, R tries to perform this reverse operation. Was this understandable?
CodePudding user response:
We may use list2env
v <- 'sum.of.ranfx'
list2env(setNames(list(vector(mode = "list", length = 122)), v), .GlobalEnv)
-checking the object
> head(sum.of.ranfx)
[[1]]
NULL
[[2]]
NULL
[[3]]
NULL
[[4]]
NULL
[[5]]
NULL
[[6]]
NULL
CodePudding user response:
For curious future readers, here is what I was doing wrong: attaching the wrong package. I needed library(rlang)
in addition to library(dplyr)
, and I was confused by the fact that one piece of example code on the internet was explicitly showing dplyr being attached, and not rlang, but that's not a feature of the SO answer I linked in the question. When rlang is attached it runs without error.