如何在R中替换多个字母数字字符?

时间:2016-09-22 09:47:23

标签: r

在数据框DF中,如下所示:

DF$Values

Values
B1
A
A2
B
B2
A1
C2
C1
C

我想将A2,B,B2替换为Group1,将B1,C2,C1,C替换为Group2,将A1, A替换为Group3,依此类推。这样输出数据看起来像这样

Values
Group2
Group3
Group1
Group1
Group1
Group3
Group2
Group2
Group2

我尝试使用gsub(),但它对我来说无法正常运行,就像代码一样 gsub("A1|A", "Group3" ,DF)A2替换为Group32

请帮忙!

2 个答案:

答案 0 :(得分:1)

如何为每个组创建因子水平?

df$Values <- as.factor(df$Values)
levels(df$Values) <- list(Group1= c("A2","B","B2"), Group2= c("B1","C2","C1","C"),
                                                    Group3 = c("A1", "A"))
df$Values
#[1] Group2 Group3 Group1 Group1 Group1 Group3 Group2 Group2 Group2
#Levels: Group1 Group2 Group3

答案 1 :(得分:0)

我们可以使用ifelse进行%in%(目前尚不清楚OP的帖子中是否有任何具体模式)将元素重新编码为不同的元素。

with(DF, ifelse(Values %in% c("A2", "B", "B2"), "Group1",
       ifelse(Values %in% c("B1", "C2", "C1", "C"), "Group2", "Group3")))
#[1] "Group2" "Group3" "Group1" "Group1" "Group1" "Group3" "Group2" "Group2" "Group2"