user13047041
user13047041

Reputation: 55

Replace NA with if-else in DataFrame in r

I am trying to replace NA in a column with "A", "B", or "C" based on values from another column by using if-else in DataFrame.

I tried:

df$grade[is.na(df$grade)] <- ifelse(df$score >= 28, "C", ifelse(df$score < 14, "A", "B"))

But got an error:

number of items to replace is not a multiple of replacement length

Then, I tried another code:

df1 <- replace(is.na(df$grade), ifelse(df$score >= 28, "C", ifelse(df$score < 14, "A", "B")))

But also got an error:

Error in replace(is.na(df$grade), ifelse(df$score >= 28, "C", : argument "values" is missing, with no default

Can anyone please explain to me why I got these error and how to fix them?

Truly appreciate any help :)

Upvotes: 0

Views: 998

Answers (2)

akrun
akrun

Reputation: 886938

We can use fcase from data.table

library(data.table)
setDT(df)[, grade := fcase(is.na(grade), grade,
                          score >= 28, 'C',
                          score < 14, 'A',
                            'B')]

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388797

You need to subset score as well.

inds <- is.na(df$grade)
df$grade[inds] <- with(df,ifelse(score[inds] >= 28, "C", ifelse(score[inds] < 14, "A", "B")))

Probably, using case_when would make it cleaner.

library(dplyr)
df %>%
  mutate(grade = case_when(!is.na(grade) ~ grade, 
                           score >= 28 ~ "C",
                           score < 14, "A", 
                           TRUE ~ "B"))

Upvotes: 2

Related Questions