简体   繁体   中英

Subset list into elements and assign consecutive labels in r

I have a list of character elements (party_list). I want to subset this into separate character vectors of each element and assign them a name party_list_1, party_list_2 etc...

party_list looks like the following (with more than just the two elements)

 party_list
 [[1]]
    [1] "Social Democratic and Labour Party" "DUP"  "Social Democratic and Labour Party"
    [4] "DUP"

 [[2]]
    [1] "Social Democratic and Labour Party" "DUP"  "Social Democratic and Labour Party"
    [4] "DUP"

I can extract each element individually through party_list_1 <- party_list[[1]] which gives me the first element, however, I don't want do this for every element.

party_list_1
[1] "Social Democratic and Labour Party" "DUP"  "Social Democratic and Labour Party"
[4] "DUP"

I'd like to end up with individual character vectors for each element in the original list. I assume it could be done using a for loop but can't work it out (obviously the below is wrong, but I would like the "i" to iterate creating a new vector for each element

for (i in 1:length(party_list)) {
 party_list_i <- party_list[[i]]

}

This can be done with assign , but that's generally not advised. Why do you want it outside the list and in separate vectors? Maybe there's a better way of achieving what you want to do?

for (i in 1:length(party_list)) {
  assign(paste0("party_list_",i),party_list[[i]])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM