‘!’ not meaningful for factors in R

前端 未结 2 393

I need to exclude the variable \"PABI\" from my data frame. So, I am subsetting as follow:

MyData4 <- subset(MyData, PROV==\"PABI\")
newdata <- MyData[!MyD         


        
相关标签:
2条回答
  • 2021-01-29 15:51

    Why not just do:

    newdata <- subset(MyData, PROV!="PABI")
    
    0 讨论(0)
  • 2021-01-29 15:55

    ! only applies to logical variables. However, your subset call returns a data.frame, not a logical; hence the error. In reality, you just need to invert the condition in your first line:

    newdata <- subset(MyData, PROV != "PABI")
    

    That’s it.

    Just to clarify how logical values work, you could also write the following:

    has_PABI <- MyData$PROV == "PABI"
    newdata <- MyData[! has_PABI]
    

    Notice that the second line is now identical to your code. What changed is that the variable you as a negative index is now a logical vector, containing the values TRUE or FALSE for each row, depending on the value of that row’s PROV column.

    0 讨论(0)
提交回复
热议问题