Reputation: 127
I got two list
var1=c("fe1","fe2")
var2=c("A1","A2")
I try to do that with a loop for
list_final <- list("fe1" = "A1", "fe2" = "A2")
My code is there
library("rlist")
list_final <-list()
for(i in var1) {
for(d in var2) {
x = setNames(i, paste0(d))
list.append(list_final,x)
}
}
But the list is always empty
Upvotes: 1
Views: 52
Reputation: 101848
If you have unique values in var1
, you can try the code below with split
> split(var2,var1)
$fe1
[1] "A1"
$fe2
[1] "A2"
Otherwise, the method by @akrun should be applied
Upvotes: 0
Reputation: 39603
Also a loop approach can be useful:
#Data
var1=c("fe1","fe2")
var2=c("A1","A2")
#List
List <- list()
#Loop
for(i in 1:length(var1))
{
List[[var1[i]]]<-var2[i]
}
List
Output:
List
$fe1
[1] "A1"
$fe2
[1] "A2"
Upvotes: 0
Reputation: 887311
We can use setNames
to create a named vector
and convert to a list
with as.list
in base R
(without using a for
loop)
list_final2 <- as.list(setNames(var2, var1))
-checking with OP's expected
identical(list_final, list_final2)
#[1] TRUE
Upvotes: 0