我需要将多个分类变量的级别转换为0,1

时间:2017-07-22 07:10:22

标签: r

我有五个列,包含2个级别,其列名称类似于c(a,b,x,y,z)。以下命令适用于1列。但我需要同时为所有五列提供它。

levels(car_data[,"x"]) <- c(0,1)
car_data[,"x"] <- as.numeric(levels(car_data[,"x"]))[car_data[,"x"]]

1 个答案:

答案 0 :(得分:0)

如果有两个级别,那么我们可以做

library(dplyr)
car_data %>%
        mutate_all(funs(as.integer(.)-1))
#  a b c 
#1 0 0 0
#2 1 1 1
#3 0 0 0
#4 1 1 1

数据

car_data <- structure(list(a = structure(c(1L, 2L, 1L, 2L), .Label = c("a", 
"b"), class = "factor"), b = structure(c(1L, 2L, 1L, 2L), .Label = c("a", 
"b"), class = "factor"), c = structure(c(1L, 2L, 1L, 2L), .Label = c("a", 
"b"), class = "factor")), .Names = c("a", "b", "c"), row.names = c(NA, 
-4L), class = "data.frame")