I want to map a vector to the key-value list. I would like to get a list using purrr:map (or other tidyverse method) where keys would be the characters before the first comma and values (vectors) the rest of characters. My solution using a for loop:
v <- c("a,1,2", "b,4,5,6", "c,x")
l <- list()
for(vv in v) {
vv_split <- vv %>% stringr::str_split(",")
l[[vv_split[[1]][1]]] <- vv_split[[1]][-1]
}
Here is one option with read.csv
and split
df1 <- read.csv(text = v, header = FALSE, stringsAsFactors = FALSE)
lapply(split(df1[-1], df1[,1]), function(x) na.omit(unlist(x, use.names = FALSE)))
Or another option with tidyverse
library(dplyr)
library(tibble)
library(tidyr)
enframe(v) %>%
separate_rows(value) %>%
group_by(name) %>%
mutate(name1 = value[1]) %>%
slice(-1) %>%
ungroup %>%
select(-name) %>%
unstack(value ~ name1)
#$a
#[1] "1" "2"
#$b
#[1] "4" "5" "6"
#$c
#[1] "x"
Or with str_remove
and str_replace
str_remove(v, '.,') %>%
strsplit(',') %>%
set_names(str_extract(v, '.'))
#$a
#[1] "1" "2"
#$b
#[1] "4" "5" "6"
#$c
#[1] "x"
I think a bit simpler solution is
library(tidyverse)
v <- c("a,1,2", "b,4,5,6", "c,x")
# Split each string into its character elements
l <- str_split(v, ",") %>%
# Extract the first element to use as the list element name
set_names(., map(., 1)) %>%
# Remove the first element
map(tail, -1)
l
# > $a
# > [1] "1" "2"
# >
# > $b
# > [1] "4" "5" "6"
# >
# > $c
# > [1] "x"
Though the set_names
step could use some improvement in readability.
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.