如何在R中创建虚拟变量

时间:2012-09-11 02:40:39

标签: r

我正在尝试通过从HOUSE列中提取数字来为“好”和“坏”创建一个虚拟变量。我想要做的是,如果HOUSE栏中的值是1,2,9,那么房子是“好的”,否则“坏”)

我粘贴了data.frame对象的dput输出。

## dput output assigned to the housetype variable

structure(list(Price = c(10L, 20L, 31L, 41L, 52L, 63L, 45L, 63L, 
64L, 45L), Location = structure(c(4L, 7L, 6L, 3L, 2L, 4L, 5L, 
1L, 6L, 8L), .Label = c("AK", "ATL", "BOS", "DC", "GA", "MA", 
"NYC", "PA"), class = "factor"), HOUSE = c(1L, 1L, 1L, 2L, 6L, 
7L, 8L, 9L, 10L, 11L)), .Names = c("Price", "Location", "HOUSE"
), class = "data.frame", row.names = c(NA, -10L))

如何以每个变量仍包含其他信息的方式创建虚拟变量? (价格和位置)

感谢!!!

1 个答案:

答案 0 :(得分:6)

您可以这样做:

housetype$quality <- ifelse(housetype$HOUSE %in% c(1,2,9), "good", "bad")
housetype
#        Price Location HOUSE quality
# 1     10       DC     1    good
# 2     20      NYC     1    good
# 3     31       MA     1    good
# 4     41      BOS     2    good
# 5     52      ATL     6     bad
# 6     63       DC     7     bad
# 7     45       GA     8     bad
# 8     63       AK     9    good
# 9     64       MA    10     bad
# 10    45       PA    11     bad

最好不要创建字符向量(“好”或“坏”),而是创建一个标志变量,即逻辑类型的向量(TRUE或FALSE)。它使用更少的内存,通常更容易使用:

housetype$is.good <- housetype$HOUSE %in% c(1,2,9)
housetype
#    Price Location HOUSE quality is.good
# 1     10       DC     1    good    TRUE
# 2     20      NYC     1    good    TRUE
# 3     31       MA     1    good    TRUE
# 4     41      BOS     2    good    TRUE
# 5     52      ATL     6     bad   FALSE
# 6     63       DC     7     bad   FALSE
# 7     45       GA     8     bad   FALSE
# 8     63       AK     9    good    TRUE
# 9     64       MA    10     bad   FALSE
# 10    45       PA    11     bad   FALSE