我有一个向量(数据框列,...)像
labels <- c("127_500", "128_500","13_200")
我想创建一个如下所示的向量:
new vector <- c("127_500" = "500",
"128_500" = "500",
"131_200" = "200")
所以,我基本上在“_”处分割原始分割并保留第二部分并创建类似命名向量的东西:
> new_vector
127_500 128_500 131_200
"500" "500" "200"
这可能吗? 我需要在ggplot中使用
new_vector
作为scale_x_discrete
中的标签信息。我有几百个输入字符串。
不使用正则表达式的解决方案:
setNames(sapply(strsplit(labels, '_'), `[`, 2), labels)
# 127_500 128_500 13_200
# "500" "500" "200"
setNames(stringr::word(labels, 2, sep = '_'), labels)
# 127_500 128_500 13_200
# "500" "500" "200"