简体   繁体   English

Map 向量到键值列表使用 purrr:map

[英]Map vector to key-value list using purrr:map

I want to map a vector to the key-value list.我想 map 一个向量到键值列表。 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.我想使用 purrr:map (或其他 tidyverse 方法)获取一个列表,其中键是第一个逗号之前的字符,值(向量)是字符的 rest。 My solution using a for loop:我使用 for 循环的解决方案:

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这是read.csvsplit的一个选项

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或者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_removestr_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.尽管set_names步骤可以提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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