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!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.