【发布时间】: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 <- NULL和bb <- NULL不是必需的。 -
谢谢,我在打字时错过了它,刚刚更新了代码。实际上,我遇到了错误。
标签: r dplyr dummy-variable hmisc