如何用R中的条件语句替换行值

时间:2019-04-03 09:09:09

标签: r replace

我有3列Seq,Period和Treatment。 序列具有值ABB,BBA,BAB ..即1A和2B组合。 期间有3个值,即1,2和3 根据周期和顺序,治疗将具有价值 例如。如果Sequence为ABB,Period为1,则处理为A 如果序列为ABB且周期为2,则治疗将为B 同样,如果Sequence为ABB,Period为3,则处理将为B。 以下是数据的快照

 Sequence Period Treatment   
    BBA      1         B  
    BBA      2         B  
    BBA      3         A 
    ABB      1         A 
    ABB      2         B 
    ABB      3         B

我要用B1替换序列BBA和周期1的治疗值B,并用B2替换序列BBA和周期2的治疗值 与其余数据类似。

我尝试了以下代码

updatedata<-if((data$Sequence=='ABB' && data$Period==2) || (data$Sequence=='BAB' && data$Period==1) || (data$Sequence=='BBA' && data$Period==1)){
  data$Treatment<-'B1'
}else if((data$Sequence=='ABB' && data$Period==3) || (data$Sequence=='BAB' && data$Period==3) || (data$Sequence=='BBA' && data$Period==2)){
data$Treatment<-'B2'
}else((data$Sequence=='ABB' && data$Period==1) || (data$Sequence=='BAB' && data$Period==2) || (data$Sequence=='BBA' && data$Period==3)){
data$Treatment<-'A'}

我希望得到以下结果

Sequence Period Treatment   
    BBA      1         B1  
    BBA      2         B2 
    BBA      3         A 
    ABB      1         A 
    ABB      2         B1
    ABB      3         B2

但是我遇到以下错误:

  

错误:“ data $ Treatment <-'B2'中出现意外的'{'    } else((data $ Sequence =='ABB'&& data $ Period == 1)||    (data $ Sequence =='BAB'&& data $ Period == 2)|| (data $ Sequence =='BBA'&&    data $ Period == 3)){“

1 个答案:

答案 0 :(得分:1)

使用dplyr

z%>%mutate(Treatment=if_else(Treatment=="B",paste0("B",Period),Treatment))

1      BBA      1        B1
2      BBA      2        B2
3      BBA      3         A
4      ABB      1         A
5      ABB      2        B2
6      ABB      3        B3

修改

第二个版本:

cond1 = z$Sequence=="BBA" & z$Treatment=="B"
cond2 = z$Sequence=="ABB" & z$Treatment=="B"
cond3 = z$Sequence=="BAB" & z$Treatment=="B"

z$Treatment[cond1]=paste0(z$Treatment[cond1],z$Period[cond1])
z$Treatment[cond2]=paste0(z$Treatment[cond2],z$Period[cond2]-1)
z$Treatment[cond3]=paste0(z$Treatment[cond3],
                          ifelse(z$Period[cond3]>2,2,1))
> z
   Sequence Period Treatment
2       BBA      1        B1
3       BBA      2        B2
4       BBA      3         A
5       ABB      1         A
6       ABB      2        B1
7       ABB      3        B2
8       BAB      1        B1
9       BAB      2         A
10      BAB      3        B2

数据:

structure(list(Sequence = c("BBA", "BBA", "BBA", "ABB", "ABB", 
"ABB", "BAB", "BAB", "BAB"), Period = c(1, 2, 3, 1, 2, 3, 1, 
2, 3), Treatment = c("B1", "B2", "A", "A", "B1", "B2", "B1", 
"A", "B2")), row.names = 2:10, class = "data.frame")