-1

I have a variable "dif2" in data2, and I'm going to add a new variable to the dataset named "L" with the condition that ( if -0.1 <= dif2 <= 0.1, L == "B", while if dif2 > 0.1, then L == "S", and if dif2 <-0.1 then L == "E")

I tried different ways. First I used for loop :

for (i in 1:nrow(data2)) {
    if(!is.na(data2$dif2[i] < -0.1)){
            data2[i,'L'] <- "E"
    }
    else if (!is.na(data2$dif2[i] > 0.1)) {
            data2[i, 'L'] <- "S"
    }
    else if (!is.na(data2$dif2[i] <= 0.1 && data2$dif2[i] >= -0.1)) {data2[i, 'L'] <- "B"
    }

}

This didn't work well.

And Then I used recoding directly like this:

data2$dif2[data2$dif2 < -0.1] <- "E"
data2$dif2[data2$dif2 > 0.1] <- "S"
data2$dif2[data2$dif2 >= -0.1 && data2$dif2 <= 0.1] <- "B"

This didn't work well either (some number between -0.1 and 0 was not correctly coded)

zx8754
  • 52,746
  • 12
  • 114
  • 209
LeoNiu
  • 13
  • 1
  • 3

1 Answers1

0

While recoding you should replace value in coulmn L based on dif2.

    # creating data
    data2<-data.frame("dif2"=c(-0.2,0.2,0.05))
    data2
       dif2
    1 -0.20
    2  0.20
    3  0.05
   #recoding
   data2$L[data2$dif2>0.1]<-"S"
   data2$L[data2$dif2 < -0.1] <- "E"
   data2$L[data2$dif2 >= -0.1 & data2$dif2 <= 0.1] <- "B"
   data2
      dif2 L
   1 -0.20 E
   2  0.20 S
   3  0.05 B

Or ifelse

data2$L<-ifelse(data2$dif2 > 0.1, "S","B")
data2$L<-ifelse(data2$dif2 < -0.1, "E",data2$L)
> data2
   dif2 L
1 -0.20 E
2  0.20 S
3  0.05 B

Or using cut

data2$L<-cut(data2$dif2, breaks = c(-Inf,-0.1,0.1,Inf),labels=c("E","B","S"))
rar
  • 894
  • 1
  • 9
  • 24