conditionals (if, else if, else)

Hi, people!
I will appreciate that someone could help me with this problem. I have a data with 4 columns and I want to create the 5 th new with some condictions.

This input data is in data.frame format is:

ALT_ORT,ALTGEOM,ALT_NORMAL,N,
2.8,,,-33.62,
3.2,,,-33.65,
,,46.4603,-7.88,
514.17,,,-6.09,

I tried to used this scrip

   if (is.na("ALTGEOM")==FALSE){
     t1$ALTGEOM2 <-  t1$ALTGEOM
     } else if (is.na("ALT_ORT")==FALSE) {
       t1$ALTGEOM2 <-t1$ALT_ORT+ t1$N
       } else {
         t1$ALTGEOM2 <-t1$ALT_NORMAL + t1$N
	}

And I would like this output file:

ALT_ORT,ALTGEOM,ALT_NORMAL,N,ALTGEOM2
2.8, , ,-33.62,-30.82
3.2, , ,-33.65,-30.45
, ,46.4603,-7.88, 38.5803
,514.17, , ,514.17

However, the real output is that:

ALT_ORT,ALTGEOM,ALT_NORMAL,N,ALTGEOM2
2.8, , ,-33.62,
3.2, , ,-33.65,
, ,46.4603,-7.88,
,514.17, , ,514.17

Does someone knows how can I do?

Thanks in advanced,

Elaine Loureiro

Hi, welcome!

To help us help you, could you please turn this into a proper reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

2 Likes

I took a stab at solving this without a reproducible example. If this does not solve your problem, please do make a reprex as andresrcs requested.

I used the case_when function of dplyr and I modified your description of the initial t1 to get the desired output.

library(dplyr)
t1 <- read.csv("c:/users/fjcc/Documents/R/Play/Dummy.csv")
t1
#>   ALT_ORT ALTGEOM ALT_NORMAL      N
#> 1     2.8      NA         NA -33.62
#> 2     3.2      NA         NA -33.65
#> 3      NA      NA    46.4603  -7.88
#> 4      NA  514.17         NA  -6.09
t1$ALTGEOM2 <- case_when(
  !is.na(t1$ALTGEOM) ~ t1$ALTGEOM, 
  !is.na(t1$ALT_ORT) ~ t1$ALT_ORT + t1$N,
  TRUE ~ t1$ALT_NORMAL + t1$N
  )


t1
#>   ALT_ORT ALTGEOM ALT_NORMAL      N ALTGEOM2
#> 1     2.8      NA         NA -33.62 -30.8200
#> 2     3.2      NA         NA -33.65 -30.4500
#> 3      NA      NA    46.4603  -7.88  38.5803
#> 4      NA  514.17         NA  -6.09 514.1700

Created on 2019-09-23 by the reprex package (v0.2.1)

3 Likes

I tested this solution and solve the problem. Thanks a lot!

Thanks for your orientation, however FJCC solved the problem. In the next question, I will use the procedure and generate a good dataset for testing.

Thanks a lot!

elanlour

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.