Reputation: 51
I'm having 3 columns Seq, Period and Treatment. Sequence has values ABB,BBA,BAB,.. i.e. 1A and 2B combination. Period has 3 values i.e. 1,2 & 3 and Treatment will have value based on the Period and Sequence eg. if Sequence is ABB and Period is 1 then Treatment will be A if Sequence is ABB and Period is 2 then Treatment will be B similarly if Sequence is ABB and Period is 3 then Treatment will be B. following is the snapshot of the data
Sequence Period Treatment
BBA 1 B
BBA 2 B
BBA 3 A
ABB 1 A
ABB 2 B
ABB 3 B
I want to Replace Treatment Value B of Sequence BBA and Period 1 with B1 and Sequence BBA and Period 2 with B2 similarly with the rest of the data.
I tried the following code
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'}
I expect the following results
Sequence Period Treatment
BBA 1 B1
BBA 2 B2
BBA 3 A
ABB 1 A
ABB 2 B1
ABB 3 B2
But I'm getting the following error:
Error: unexpected '{' in: " data$Treatment<-'B2' }else((data$Sequence=='ABB' && data$Period==1) || (data$Sequence=='BAB' && data$Period==2) || (data$Sequence=='BBA' && data$Period==3)){"
Upvotes: 0
Views: 68
Reputation: 2467
Using 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
Edit
Second version:
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
data:
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")
Upvotes: 1