vrige
vrige

Reputation: 319

R how can I comment a variable through its string name?

x <- "y"
assign(x,4)

comment(get(x))<-"this is a comment!"

how can i do something like this? i tried also

comment(x) <-"this is a comment!"

and my others, but it doesn't seem to work. Similar to this question: Access variable value where the name of variable is stored in a string

Upvotes: 0

Views: 130

Answers (2)

Nik
Nik

Reputation: 495

eval(
  substitute(
    expr = comment(temp) <- "this is a comment!",
    env = list(temp = as.name(x))
  )
)

str(y)

Output:

 num 4
 - attr(*, "comment")= chr "this is a comment!"

Upvotes: 0

thc
thc

Reputation: 9705

Use a temporary variable and then re-assign it:

x <- "y"
assign(x,4)
temp_x <- get(x)
comment(temp_x) <- "this is a comment!"
assign(x, temp_x)

Upvotes: 2

Related Questions