簡體   English   中英

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

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

我想 map 一個向量到鍵值列表。 我想使用 purrr:map (或其他 tidyverse 方法)獲取一個列表,其中鍵是第一個逗號之前的字符,值(向量)是字符的 rest。 我使用 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]
}

這是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)))

或者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"

或使用str_removestr_replace

str_remove(v, '.,') %>% 
      strsplit(',') %>% 
      set_names(str_extract(v, '.'))
#$a
#[1] "1" "2"

#$b
#[1] "4" "5" "6"

#$c
#[1] "x"

我認為一個更簡單的解決方案是

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"

盡管set_names步驟可以提高可讀性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM