转换R中的值

时间:2015-05-26 05:57:36

标签: r

enter image description here

我想将我的NA转换为0,将其他值转换为1而不影响我的ID变量

1 个答案:

答案 0 :(得分:8)

你可以尝试

df1[-1] <- (!is.na(df1[-1]))+0L
df1
#  ID condimenti occhialli pane prontoTaway surgelati utensili
#1  1          0         0    1           0         0        0
#2  2          0         1    0           0         0        0
#3  3          0         0    0           0         1        0
#4  4          0         0    0           0         1        0

或使用data.table

library(data.table)
setDT(df1)
for(j in 2:ncol(df1)){
  set(df1, i= NULL, j=j, value= (is.na(df1[[j]]))+0L)
 }

或使用dplyr

library(dplyr)
df1 %>% 
    mutate_each(funs((!is.na(.))+0L), -ID)
数据
df1 <-  structure(list(ID = 1:4, condimenti = c(NA, NA, NA, NA), 
 occhialli = c(NA, 
"CONDIMENTI PRIMI (PELATI & SUGHI)", NA, NA), pane =
c("OCCHIALI E OROLOGI", 
NA, NA, NA), prontoTaway = c(NA, NA, NA, NA), surgelati = c(NA, 
NA, "PRONTO CALDO TAKE AWAY", "PRONTO CALDO TAKe AWAY"), utensili = c(NA, 
NA, NA, NA)), .Names = c("ID", "condimenti", "occhialli", "pane", 
"prontoTaway", "surgelati", "utensili"), row.names = c(NA, -4L
), class = "data.frame")