Replace values ​​in a data frame based on another factor that contains NA in R

I have a dataframe that contains (among other things) a numeric column with concentration and a column of factors with status. This status flag contains NA files.

Here is an example

df<-structure(list(conc = c(101.769, 1.734, 62.944, 92.697, 25.091, 27.377, 24.343, 55.084, 0.335, 23.280), status = structure(c(NA, NA, NA, NA, NA, NA, 2L, NA, 1L, NA), .Label = c("<LLOQ", "NR"), class = "factor")), .Names = c("conc", "status"), row.names = c(NA, -10L), class = "data.frame") 

I want to replace the concentration column with a row for some flag column values ​​or a concentration value formatted with a certain number of significant digits.

When i try to do it

 ifelse(df$status=="NR","NR",df$conc) 

NA in the status flag does not cause a true or false condition (and return NA) - as the documentation suggests. I could iterate over the lines and use IF, then on each, but that seems inefficient.

Am I missing something? I also tried as.character (df $ status), which does not work. My mojo should be low ....

+4
source share
3 answers

Use %in% instead of == :

ifelse(df$status %in% "NR","NR", df$conc)

Comparison of two methods:

 data.frame(df, ph = ifelse(df$status=="NR","NR",df$conc), mp = ifelse(df$status %in% "NR","NR",df$conc)) 

Check in ?match for more information - I'm not sure I can explain this well.

+5
source

You must explicitly check NA so you can use:

 ifelse(df$status=="NR" | is.na(df$status),"NR",df$conc) # gives you NR for NA 

or

 ifelse(df$status=="NR" & !is.na(df$status),"NR",df$conc) # gives you df$conc for NA 
+3
source

How about missing testing:

 ifelse(is.na(df$status), df$conc, as.character(df$status)) 
+2
source

Source: https://habr.com/ru/post/1305663/


All Articles