开发者

Commenting multiple objects at once

Suppos开发者_C百科e, 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"


Try this:

# sample data
letters <- setNames(as.list(1:10), LETTERS[1:10])

for(i in 1:10) {
   temp <- letters[[i]]
   comment(temp) <- paste(i)
   letters[[i]] <- temp
}


Another variant is to get() the object and assign it to a local object. Attach the comment to that local object and then assign it back to the global workspace.

> for(x in 1:10) {
+     assign(letters[x],x)
+ }
>
> a
[1] 1
> comment(a)
NULL
>
> for(x in 1:10) { 
+     obj <- get(letters[x])
+     comment(obj) <- paste(x)
+     assign(letters[x], obj)
+ }
> ## cleanup
> rm(obj)
> a
[1] 1
> comment(a)
[1] "1"

The reason that your code didn't work is that there isn't a replacement function version of get(), hence the error message about get<-().

Storing your objects in a list as others have mentions would be easier to manage so you don't have lots of objects clogging the global workspace, but the above shows how to modify your example code to achieve the end you wanted.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜