R: How to turn characters/numeric into 1s and NAs into 0s?

前端 未结 1 466
太阳男子
太阳男子 2021-01-28 13:25

Is there an easy way to turn characters/numeric into 1 and NAs into 0 for columns? Here some example data (I want to apply this on [,3:4]):

structure(list(Item.C         


        
1条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-28 14:11

    I named the dataframe d:

    d$Item.y <- as.integer(!is.na(d$Item.y))
    d$Item.WFcode <- as.integer(!is.na(d$Item.WFcode))
    

    For many columns better:

    df[,3:4] <- ifelse(is.na(df[,3:4]), 0, 1) # or
    df[3:4] <- +(!is.na(df[3:4])) # '+' converts to integer or
    df[3:4] <- as.integer(!is.na(df[3:4]))
    

    (code from the comments from etienne and David)

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