0

I need to create a new column named "condition" (which is not there initially) based on the first three columns. If the values are from cond1 then it should be 1 in my condition column and so on. Any suggestions.

cond_test = read.csv("https://www.dropbox.com/s/du76g4vlfz2uaph/cond_test.csv?dl=1")
cond_test
#>   ï..cond1 cond2 cond3 condition
#> 1        2    NA    NA         1
#> 2        4    NA    NA         1
#> 3       NA     3    NA         2
#> 4       NA     5    NA         2
#> 5       NA     4    NA         2
#> 6       NA    NA     1         3
#> 7       NA    NA     4         3
#> 8       NA    NA     7         3

2 Answers 2

1

You can use max.col to get first non-NA value in each row.

max.col(!is.na(cond_test))
#[1] 1 1 2 2 2 3 3 3

If you have more than one non-NA value in the row you can look at ties.method argument in ?max.col on how to handle ties.


In dplyr you can use rowwise :

library(dplyr)
cond_test %>%
  rowwise() %>%
  mutate(condition = which.max(!is.na(c_across())))
Sign up to request clarification or add additional context in comments.

4 Comments

r> max.col(!is.na(cond_test)) [1] 4 4 2 4 4 4 5 3 is what I am getting. Can you please share complete code.
@RamakrishnaS I am assuming there is no condition column in your data as mentioned in your post. cond_test$condition <- NULL
I removed condition, and ran the dplyr code. I got this error. r Error: Problem with `mutate()` input `condition`. x Input `condition` can't be recycled to size 1. i Input `condition` is `which(!is.na(c_across()))`. i Input `condition` must be size 1, not 2. i Did you mean: `condition = list(which(!is.na(c_across())))` ? i The error occurred in row 1.
@RamakrishnaS Unlike the example shared you have rows in your data where there are more than 1 value. I have used whcih.max to select the 1st one.
0

I tried the following code and is working. But any elegant solutions are welcome.

cond_test$condition = ifelse(!is.na(cond_test$ï..cond1), 1, 
                             ifelse(!is.na(cond_test$cond2), 2, 3))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.