如何使用R创建基于模式匹配的向量?

时间:2018-03-14 20:26:31

标签: r design-patterns vector

在R中,我有一个包含字符的向量:

v <- c("X412A-Y423A", "X400A-Y405B", "X499A-Y448B", "X455A-Y213A")

我想基于这个创建一个向量,根据每个字符串(A或B)中的最后一个字符,新向量将具有不同的值(红色或蓝色),例如:

vnew <- c("red","blue","blue","red")

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:3)

使用基座R,您可以执行以下操作:

v <- c("X412A-Y423A", "X400A-Y405B", "X499A-Y448B", "X455A-Y213A")
n <- nchar(v)
ifelse(substr(v, n, n)=="A", "red", "blue")

或者你可以使用正则表达式(也是基础R):

ifelse(grepl("A$", v), "red", "blue")

答案 1 :(得分:1)

使用case_when包中的dplyrsub中的base-R可以实现优雅的解决方案。该解决方案更适合data.frame类场景。

#data
v <- c("X412A-Y423A", "X400A-Y405B", "X499A-Y448B", "X455A-Y213A")

library(dplyr)
data.frame(v, stringsAsFactors = FALSE) %>% 
  mutate(value = sub('.*(?=.$)', '', v, perl=T)) %>%
  mutate(color = case_when(
    .$value == 'A' ~ "Red",
    .$value == 'B' ~ "Blue",
    TRUE ~ "Green"
  ))

#             v  value color
# 1 X412A-Y423A     A   Red
# 2 X400A-Y405B     B  Blue
# 3 X499A-Y448B     B  Blue
# 4 X455A-Y213A     A   Red

仅使用颜色解决方案创建矢量可以是:

last_char = sub('.*(?=.$)', '', v, perl=T)

case_when(
  last_char == 'A' ~ "Red",
  last_char == 'B' ~ "Blue",
  TRUE ~ "Green"
)
[1] "Red"  "Blue" "Blue" "Red

答案 2 :(得分:0)

这将有效:

> v <- c("X412A-Y423A", "X400A-Y405B", "X499A-Y448B", "X455A-Y213A")
> x <- substr(v,nchar(v),nchar(v))
> vnew <- ifelse(x == "A", "red", ifelse(x == "B", "blue", ""))
> vnew
[1] "red"  "blue" "blue" "red"