Sander
Sander

Reputation: 23

change specific component of list in R

I try to change a specific component L[[2]] in a list L in R. Unfortunately, the other component L[[1]] in the list changes as well. Below is a minimal working example:

 # initialize list L:
 L <- matrix(list( matrix(0,1,2) ), 2, 1)
 # show that L[[1]] = c(0,0):
 print(L[[1]][1,])
 #>[1] 0 0
 # only change L[[2]] into c(1,1):
 L[[2]][1,]   <- 1 
 # however L[[1]] has changed too to c(1,1):
 print(L[[1]][1,])
 #>[1] 1 1

(Maybe this is a basic question as I am not an expert in R.)

In response to Akrun's comment: The change in L[[1]] occurs when I run the complete code in one go in the editor of R-studio. Somehow the change in L[1] does not occur when I run the four commands at the command line one at a time. Seems very strange to me.

Upvotes: 2

Views: 281

Answers (1)

akrun
akrun

Reputation: 887028

There are multiple ways to tackle this. The structure is a bit convoluted to make the changes as we do in regular list. It is a list with dimension attributes given by matrix and is complicated by having a list of matrices

1) The list object is created within a matrix and it is a list of matrices. So, we could assign the values based on subsetting the elements of the matrix first and then extract the list component to assign it to 1

L[2][[1]][] <- 1
print(L[[1]][1,])
#[1] 0 0

2) Another option is to create a temporary list object and assign the values on the list, update the matrix/list later with the changed list

l1 <- lapply(L, I) # I stands for identity.
l1[[2]][] <- 1
L[] <- l1
print(L[[1]][1,])
#[1] 0 0

Upvotes: 2

Related Questions