【问题标题】:error in creating dummy variables for each continuous variable in dataframe为数据框中的每个连续变量创建虚拟变量时出错
【发布时间】:2018-11-05 13:00:58
【问题描述】:

我有一个包含 10 列的数据集,这些是连续数据。通过 dput() 和下面的 shon 收集了一个相同的样本:

structure(list(x1 = c(12.800454545, 17.71, 5.805, 13.111875, 14.121428571, 12.800454545, 17.71, 5.805, 13.111875, 14.121428571), 
x2 = c(281.61, 230.23, 11.61, 209.79, 296.55, 281.61, 230.23, 11.61, 209.79, 296.55), 
x3 = c(19.41, 13.91, 0, 2.37, 23.49, 19.41, 13.91, 0, 2.37, 23.49), 
x4 = c(65L, 62L, 3L, 41L, 45L, 65L, 62L, 3L, 41L, 45L), 
x5 = c(0.571428571, 1.857142857, 21.14285714, 2.571428571, 1.428571429, 0.571428571, 1.857142857, 21.14285714, 2.571428571, 1.428571429), 
x6 = c(52L, 40L, 3L, 22L, 33L, 52L, 40L, 3L, 22L, 33L), 
x7 = c(44.53, 15.38, 5.97, 4.97, 13.94, 44.53, 15.38, 5.97, 4.97, 13.94), 
x8 = c(65L, 53L, 3L, 41L, 45L, 65L, 53L, 3L, 41L, 45L), 
x9 = c(6L, 4L, 1L, 1L, 1L, 6L, 4L, 1L, 1L, 1L), 
x10 = c(46.43, 17.52, 0, 11.73, 0, 46.43, 17.52, 0, 11.73, 0)), 
row.names = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), class = "data.frame")

我想做的是编写一个自动化函数,该函数将使用分位数将每个变量分成 5 组,并创建虚拟变量并作为列添加回数据集中。

我试图做这样的事情,但无法做到:

create a copy of dataframe to work on dummy vars creations
d1 <- df

library(dplyr)
library(Hmisc)
for (i in 1:length(d1)){
  #print(table(cut2(d1[,i], g=5)))
  aa <- NULL
  bb <- NULL

  x1 <- select(d1, i)
  aa <- cut2(x1, g=5)

  # Create dummy variables
  bb <- model.matrix(~ aa + 0, data=df)
  colnames(bb) <- gsub("aa","",colnames(bb))     #clean column names
  bb <- as.data.frame(bb)   # convert matrix to dataframe


}

【问题讨论】:

  • 请修正:cut2(, g=5) 已经错了。 aa &lt;- NULLbb &lt;- NULL 不是必需的。
  • 谢谢,我在打字时错过了它,刚刚更新了代码。实际上,我遇到了错误。

标签: r dplyr dummy-variable hmisc


【解决方案1】:

如果你用 dummy 你的意思是你观察的分位数等级,一个解决方案可以是:

for (i in 1:length(df)){
                        d1[,i] <- as.integer(cut2(df[,i], g=5)) 
}

【讨论】:

  • 谢谢,这个函数的作用是创建分位数排名并用排名替换列中的值。我需要创建新列(假人),比如 x1_d1、x1_d2、x1_d3 等等,并且这些列中的每一个都有 0 或 1,具体取决于原始列 x1 中的等级。我想,我可以在那里使用“assign()”函数来做到这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 2021-07-16
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 2019-11-09
  • 1970-01-01
相关资源
最近更新 更多