artfin artfin - 3 months ago 7
R Question

Assigning value to the list element in R

Suppose I have a list of elements, and I want to change one of the elements but can't directly call the list by its name (I can only construct it as a string).

x_1 <- list()
for (i in 1 : 5) {
x_1[[i]] <- i
}

assign(eval(as.name(paste0("x_", 1)))[[1]], 6)


Using this long construction of
assign
-
eval
-
as.name
-
paste
gives the error:
"first argument is wrong"
.

How do I do it properly? And why doesn't this construction work?

Answer

You can do this by constructing the assignment expression using <- and then using eval(parse(text=x)):

x_1 <- as.list(1:5)
eval(parse(text=paste0("x_1[[1]] <-", 123)))

x_1
## 
## [[1]]
## [1] 123
## 
## [[2]]
## [1] 2
## 
## [[3]]
## [1] 3
## 
## [[4]]
## [1] 4
## 
## [[5]]
## [1] 5

If you want to pass the index as a variable, this might be simpler:

eval(parse(text=sprintf('x_1[[%s]] <- %s', 1, 123)))