When trying to replace values, “missing values are not allowed in subscripted assignments of data frames”

前端 未结 6 1511
日久生厌
日久生厌 2021-02-01 14:31

I have a table that has two columns: whether you were sick (H01) and the number of days sick (H03). However, the number of days sick is NA if H01 == false, and I would like to s

6条回答
  •  伪装坚强ぢ
    2021-02-01 15:02

    Simply use the subset() function to exclude all NA from the string.

    It works as x[subset & !is.na(subset)]. Look at this data:

    > x <- data.frame(a = c(T,F,T,F,NA,F,T, F, NA,NA,T,T,F),
    >                 b = c(F,T,T,F,T, T,NA,NA,F, T, T,F,F))
    

    Subsetting with [ operator returns this:

    > x[x$b == T & x$a == F, ]
    
             a    b
    2    FALSE TRUE
    NA      NA   NA
    6    FALSE TRUE
    NA.1    NA   NA
    NA.2    NA   NA
    

    And subset() does what we want:

    > subset(x, b == T & a == F)
    
          a    b
    2 FALSE TRUE
    6 FALSE TRUE
    

    To change the values of subsetted variables:

    > ss <- subset(x, b == T & a == F)
    > x[rownames(ss), 'a'] <- T
    
    > x[c(2,6), ]
    
         a    b
    2 TRUE TRUE
    6 TRUE TRUE
    

提交回复
热议问题