问题
I have a very simple question but I've stocked in it! I have a list as an output :
as an example :
lapply(1:40, function(x){ (1+x)})
output:
[[1]]
[1] 2
[[2]]
[1] 3
[[3]]
[1] 4
till
[[40]]
[1] 41
I wondered how can I assign each of the outputs of this list to a new variable by using a loop? something like this
a<- [[2]]; b <- [[3]]; ... az <- [[40]]
and so one.
Thanks in advance,
回答1:
Here is my solution, it requires that your output of lapply
is stored with the name ll
but it can be easily modified I think.
ll <- lapply(1:40, function(x){ (1+x)})
nam <- "list_output_"
val <- c(1:length(ll))
for(i in 1:length(val)){
assign(
paste(nam, val, sep = "")[i], ll[[i]]
) }
The output will be list_output_1
and so on.
回答2:
I created a vector for the names and used a short loop. Maybe someone can vectorize it.
var_names <- c(letters, paste0(letters[1],letters[1:13]))
for(i in seq_along(var_names)) {
assign(var_names[i], lapply(1:40, function(x){ (1+x)})[[i+1]])}
a
[1] 3
b
[1] 4
am
[1] 41
来源:https://stackoverflow.com/questions/31139169/how-to-saveassign-the-output-from-lapply-into-individual-variables-in-r