0

I am looking to create a list of vectors to which I want to assign specific value. I know I can do something like

var_list=c(V1, V2...etc)

Then use var_list[i] in a for loops. To do this thought, I have to manually creates the list at first, which is long. I know I can do something like

for(i in 1:n){
    assign(paste("Mx", i, sep = ""), i)
}

This will creates my variable name. Trouble is, how do I manage them? I would like a way to do something like this :

for(i in 1:n){
    attributes(assign(paste("Mx", i, sep = ""), i))<-list(dim=1:n)
    "here I would like to append the newly created variable (Mx"i") into a list so I could manage the whole thing later on".
}

So I could do :

for (k in 1:n){
for (j in 1:m)
new_list[[k]][j]<-other_list[[k]][(j-1)*3+1]
}

Any1 got a idea? The basic problem is that I have this long list of vector (which is represented here by "other_list"). Each vector in this list has 36 entry. I want to divide each of these vector in three different vector (I need to specify the specific value of the vector from "other_list" I want to apply to the specific value of the vector of the " new_list ". Thanks !

1
  • 1
    assign is not a function which should be used by beginners. It usually offers only an apparent solution that makes subsequent steps only harder for you. Commented Mar 23, 2016 at 14:52

1 Answer 1

1

Just pre-allocate the list and assign its names:

n <- 10
#pre-allocate list
mylist <- vector(n, mode = "list")
#assign names
names(mylist) <- paste0("Mx", seq_len(n))

#fill the list
for(i in 1:n){
 mylist[[i]] <- i
}

mylist[1:3]
#$Mx1
#[1] 1
#
#$Mx2
#[1] 2
#
#$Mx3
#[1] 3

PS: You should learn to use lapply for such tasks.

setNames(lapply(seq_len(n), identity), paste0("Mx", seq_len(n)))

And the optimal solution for the specific example is this:

setNames(as.list(seq_len(n)), paste0("Mx", seq_len(n)))
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thanks for the answer! I did as you suggested but it did not work at the "assign names" step. When I enter the code " names(mylist)<-paste0("Mx",seq_len(n)) " then run it, it doesn't show any warning message. Then I type in to display "mylist" in the console, and it displays it like this: $<NA> NULL $<NA> NULL
... oh well, now it worked... I had erased all the memory thought. Thanks alot :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.