Suppose, you have a list of variables a through j
for(x in 1:10) {
assign(letters[x],x)
}
How would you go about commenting those recently created objects? I've tried something like:
for(x in 1:10) {
comment(get(letters[x])) <- paste(x)
}
But that seems to fail. With:
Error in comment(get(letters[x])) <- paste(x) :
could not find function "get<-"
What am I missing here?
If you are ever gong to want to loop over things, then store them in a list. It makes life easier. But if you really want to do this, you might just need a loop over an eval(parse( thingum:
> for(i in 1:10){
+ eval(parse(text=paste("comment(",letters[i],")<-'",as.character(i*2),"'",sep="")))
+ }
You cannot assign a value to a returned variable, see:
> x <- 'cars'
> get(x) <- 1
Error in get(x) <- 1 : could not find function "get<-"
But reading/loading the comment of a returned variable is possible with get, see:
> comment(cars) <- "test"
> comment(get(x))
[1] "test"
You might concatenate your variables to e.g. a list and comment the elements of the list, like:
> l <- list(a=1,b=2,c=3)
> for (x in 1:3) {
+ comment(l[[letters[x]]]) <- paste(x)
+ }
> str(l)
List of 3
$ a: atomic [1:1] 1
..- attr(*, "comment")= chr "1"
$ b: atomic [1:1] 2
..- attr(*, "comment")= chr "2"
$ c: atomic [1:1] 3
..- attr(*, "comment")= chr "3"
And if you insist on using different variables, just attach the given list, like:
> attach(l)
The following object(s) are masked _by_ '.GlobalEnv':
a, b, c
> a
[1] 1
> str(a)
atomic [1:1] 1
- attr(*, "comment")= chr "1"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With