0

I have a large data frame that has a lot of string values that I want to clean.

Example:

    students <- data.frame(name = c("John", "Jerry", "Bill", "Tom", "Mary", "Bill"),
                       class = c("A", "B", "-", "#NA", "A", "low"), stringsAsFactors = FALSE)

I want every student who is not in class A,B or C to be set to D. My current solution is:

'%!in%' <- function(x,y)!('%in%'(x,y))
for(i in 1:nrow(students)) {
  if(students$class[i] %!in% c("A", "B", "C")) {
    students$class[i] <- "D"
  }
}

Is there a better solution than this, preferably with piping as there are a number of columns like this?

Thanks!

tonyk
  • 348
  • 5
  • 22
  • Another way is by `replace`, `students$class <- replace(students$class, !students$class %in% c("A", "B", "C"), "D")` or with `ifelse`, `students$class <- ifelse(students$class %in% c("A", "B", "C"), students$class, "D")` – Ronak Shah Feb 15 '17 at 12:51
  • Or very similarly `students %>% mutate(class = if_else(class %in% LETTERS[1:3], class, "D"))` – Axeman Feb 15 '17 at 13:23
  • Also see `forcats::fct_other`. – Axeman Feb 15 '17 at 13:25
  • @Axeman Thanks very much for the answer! If you want to submit your comment as an answer I will accept it as the best. – tonyk Feb 15 '17 at 13:50

1 Answers1

1

We can do this without a loop as assignment is vectorized

students$class[students$class %!in% c("A", "B", "C")] <- "D"
students
#   name class
#1  John     A
#2 Jerry     B
#3  Bill     D
#4   Tom     D
#5  Mary     A
#6  Bill     D
akrun
  • 874,273
  • 37
  • 540
  • 662