0

我在做一个简单的任务时遇到了麻烦:

假设我使用这些库并拥有这个数据框:

library(tidyverse)
library(dataPreparation)

df <- data.frame(col1 = 1, col2 = rnorm(1e1), col3 = sample(c(1, 2), 1e1, replace = TRUE))
df$col4 <- df$col2
df$col5[df$col3 == 1] = "a"
df$col5[df$col3 == 2] = "b"
df$col6 = c("b","b","a","a","b","a","a","a","a","b")
df$col7 = "d"
df$col8 = c(3,3,5,5,3,5,5,5,5,3)
df$col9 = c("x","x","y","y","x","y","y","y","y","x")
df$col10 = c("p","p","q","p","q","q","p","p","q","q")
df$col11 = c(10.5,10.5,11.37,10.5,11.37,11.37,10.5,10.5,11.37,11.37)
df <- df %>% mutate_if(is.character,as.factor)

使用以下命令,我想从 df 中删除第 4、5、7、8、9、11 列。

whichAreBijection(df)
[1] "whichAreBijection: col7 is a bijection of col1. I put it in drop list."
[1] "whichAreBijection: col4 is a bijection of col2. I put it in drop list."
[1] "whichAreBijection: col5 is a bijection of col3. I put it in drop list."
[1] "whichAreBijection: col8 is a bijection of col6. I put it in drop list."
[1] "whichAreBijection: col9 is a bijection of col6. I put it in drop list."
[1] "whichAreBijection: col11 is a bijection of col10. I put it in drop list."
[1] "whichAreBijection: it took me 0.08s to identify 6 column(s) to drop."
[1]  4  5  7  8  9 11

我可以使用手动删除它们

df$col4 = NULL
df$col5 = NULL
df$col7 = NULL
df$col8 = NULL
df$col9 = NULL
df$col11 = NULL

但是,我希望算法自动执行此操作。

我首先尝试以下方法来生成包含 whichAreBijection 提出的列号的数据框 m,然后最终将其从 df 中删除,但它让我无处可去:

x <- whichAreBijection(df)
y <- length(x)

m <- as.data.frame(matrix(0, ncol = y, nrow = nrow(df)))
i = 1
while (i< y+1) {
  # z <- names(df)[x[i]]
  m[,i] <- df[,x[i]]
  i<- i+1
}

上面生成的 m 具有由 4、5、7、8、9、11 给出的常量条目

我看到使用一个简单的命令,比如

m[,1] <- df[,4]

完美地将 m 的第一列替换为 df 的第四列。

我遇到的第二个问题是在 m 中使用与 df 中相同的列名。可能这听起来要完成简单的任务还有很长的路要走。

  1. 为什么没有在 m 中完全替换列?

  2. 我怎样才能自动让 m 选择要删除的 df 的列名作为列名?

  3. 有没有更好的方法来避免这种混乱并直接删除 whichAreBijection 提出的列名?

4

1 回答 1

0

我能够使用以下方法解决问题 1:

x <- whichAreBijection(df)
y <- length(x)
m <- as.data.frame(matrix(0, ncol = y, nrow = nrow(df)))
i = 1
while (i< y+1) {
    m[,i] <- df[,x[i], with = FALSE]
    i<- i+1
}

似乎命名列索引值不起作用,而整数列索引在右侧起作用,我的意思是 x[i]。这个问题可以通过在末尾设置 = FALSE 来避免。

问题 2 是下一个挑战。

于 2020-04-10T17:35:20.317 回答