我有一个空的数据框,我试图填充。
Df1看起来像这样:
col1 col2 col3 col4 important_col1 82 193 104 86 1202 85 68 116 63 1003 78 145 10 …
你要做的是 one hot encoding 您可以轻松实现使用 model.matrix
one hot encoding
model.matrix
下面的例子应该带你到正确的方向:
df <- data.frame(important_col = as.factor(c(1:3))) df important_col 1 1 2 2 3 3 as.data.frame(model.matrix(~.-1, df)) important_col1 important_col2 important_col3 1 1 0 0 2 0 1 0 3 0 0 1
这是否解决了这个问题:
数据:
set.seed(123) df1 <- data.frame(replicate(5, sample(1:20, 10, rep=TRUE))) colnames(df1) <- c("col1", "col2", "col3", "col4", "important_col") df2 <- data.frame(replicate(20, sample(0:0, nrow(df1), rep=TRUE))) colnames(df2) <- gsub("X", "", colnames(df2)) df_fin <- cbind(df1, df2)
结果:
vecp <- colnames(df2) imp_col <- df1$important_col m <- matrix(vecp, byrow = TRUE, nrow = length(imp_col), ncol = length(vecp)) d <- ifelse(m == imp_col, 1, 0) df_fin <- cbind(df1, d)
输出:
col1 col2 col3 col4 important_col 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 1 6 20 18 20 3 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 16 10 14 19 9 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 3 9 14 13 14 9 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 4 18 12 20 16 8 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 5 19 3 14 1 4 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 6 1 18 15 10 3 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7 11 5 11 16 5 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 8 18 1 12 5 10 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 9 12 7 6 7 6 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 10 10 20 3 5 18 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0
就像Sonny提到的那样,model.matrix()应该完成这项工作。一个潜在的问题是你必须添加一些没有出现在你的important_col中的列,如下例所示:
df <- data.frame(important_col = as.factor(c(1:3, 5))) df important_col 1 1 2 2 3 3 4 5 as.data.frame(model.matrix(~.-1, df)) important_col1 important_col2 important_col3 important_col5 1 1 0 0 0 2 0 1 0 0 3 0 0 1 0 4 0 0 0 1
第二个df中缺少Col4,因为important_col不包含值4.如果需要进行分析,则必须添加col 4。