PD1 PD1 - 4 months ago 9
R Question

Multiple then conditions in a single IF loop in R

I'm pretty new to R and have some experience of working on it but not very fluent in it.
I have recently worked on a data-set on a big data set and using R 3.3.1 for the same.
In the data frame(X) ,there is a column of flag type and 2 columns of numeric type,i.e., height and weight.

The values are something like :

h w hw_flag
5.874 60.5478 0
4.874 40.5478 0
3.874 10.5478 1
2.999 6.5478 1
8.874 90.5478 0
5.111 50.5478 1
6.554 65.5478 0


I have initialised two new columns as h_1 and w_1 to 0.

X$h_1 <- 0
X$w_1 <- 0


Now, what I want is that whenever the hw_flag is 1, then h_1 and w_1 shall get the entries copied from h and w respectively and then, once the values are copied to h_1 and w_1, the corresponding h and w values should turn 0. I wish to get it all done in one loop.

Right now, I have to write 4 loops for these 4 steps.The code I have worked for is as follows and it is giving me the desired output I wish to have:

for(i in 1:nrow(X)){
if(X$hw_flag[i] == '1')
X$h_1[i] <- X$h[i];
}

for(i in 1:nrow(X)){
if(X$hw_flag[i] == '1')
X$w_1[i] <- X$w[i];
}

for(i in 1:nrow(X)){
if(X$hw_flag[i] == '1')
X$h[i] <- 0;
}

for(i in 1:nrow(X)){
if(X$hw_flag[i] == '1')
X$w[i] <- 0;
}

Output :

h w hw_flag h_1 w_1
5.874 60.5478 0 0 0
4.874 40.5478 0 0 0
0 0 1 3.874 10.5478
0 0 1 2.999 6.5478
8.874 90.5478 0 0 0
0 0 1 5.111 50.5478
6.554 65.5478 0 0 0


I tried putting all in one if loop but certainly the issue I was facing is that the first step gets executed as expected whereas, the second step doesn't work properly. I tried putting ; and line breaks via Enter but still it didn't work out.
The code I tried was following and it copied the h values to h_1 but in the next step, it did not copy the values of w to w_1 :

for(i in 1:nrow(X)) {
if(X$hw_flag[i] == '1')
X$h_1[i] <- X$h[i];
X$w_1[i] <- X$w[i];
X$h[i] <- 0;
X$w[i] <- 0;
}


So, I basically wish to know that how can I put multiple then statements for the same IF- Yes block.

Answer

No need for loops. Just find where hw_flag equals one, and copy over the data and then override h and w with zero.

xy <- read.table(text = "h        w       hw_flag  
5.874  60.5478    0
                 4.874  40.5478    0
                 3.874  10.5478    1
                 2.999  6.5478     1
                 8.874  90.5478    0
                 5.111   50.5478   1
                 6.554   65.5478   0", header = TRUE)

xy$h_1 <- 0
xy$w_1 <- 0

hwflag1 <- xy$hw_flag == 1
xy[hwflag1, c("h_1", "w_1")] <- xy[hwflag1, c("h", "w")]
xy[hwflag1, c("h", "w")] <- 0

      h       w hw_flag   h_1     w_1
1 5.874 60.5478       0 0.000  0.0000
2 4.874 40.5478       0 0.000  0.0000
3 0.000  0.0000       1 3.874 10.5478
4 0.000  0.0000       1 2.999  6.5478
5 8.874 90.5478       0 0.000  0.0000
6 0.000  0.0000       1 5.111 50.5478
7 6.554 65.5478       0 0.000  0.0000
Comments