简体   繁体   English

条件数据框突变

[英]Conditional dataframe mutations

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: 我希望将不在A,B或C类中的每个学生设置为D。我当前的解决方案是:

'%!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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM