R-将2维向量转换为1维命名向量

时间:2020-04-29 01:49:54

标签: r purrr

如何更好地做到这一点?我希望将键值对的向量转换为连接字符串,转换为以键为名称的值向量。

library(tidyverse)
library(purrr)

x <- c("key1|value1", "key2|value2")

# Current way
x_split <- x %>% str_split("\\|")
keys <- x_split %>% map(pluck(1)) %>% unlist()
values <- x_split %>% map(pluck(2)) %>% unlist()

y <- values %>% set_names(keys)

# More elegant way
y <- x %>% some_functions()

2 个答案:

答案 0 :(得分:1)

您可以在simplify = TRUE中使用str_split并使用set_names

stringr::str_split(x, "\\|", simplify = TRUE) %>% {purrr::set_names(.[, 2], .[, 1])}

#    key1     key2 
#"value1" "value2" 

答案 1 :(得分:1)

我一直很喜欢data.table::tstrsplit

library(data.table)
tstrsplit(x,"\\|") %>% {setNames(.[[2]],.[[1]])}
#    key1     key2 
#"value1" "value2"