为什么列在使用计数器虚拟变量访问时不作为一个因素读取?

Why does column not read as a factor when it is accessed with a counter dummy variable?

我创建了一个循环,用于 select 来自大型数据框的所有因子变量。但是循环不起作用,因为出于某种原因使用计数器对列进行索引不会被读取为一个因素。为什么是这样?我怎样才能让这个循环工作:

#Here's the loop:
y <- data.frame(c = 1:2661)
for (i in 1:ncol(x)){
  ifelse(is.factor(x[i]) == FALSE, y <- cbind(y, x[i]), y <- y)
}

而问题显然出在使用 "i" 来引用该列。例如:

#sample data 
df <- as.data.frame(structure(c(2L, 2L, 2L, 2L, 2L), 
                          .Label = c("female", "male"), class = "factor"))

names(df)[names(df) == "structure(c(2L, 2L, 2L, 2L, 2L), .Label = c(\"female\", \"male\"), class = \"factor\")"] <- "var"

#reference the column name directly
is.factor(df$var)
[1] TRUE
#use a counter to access the variable:
i <- 1
is.factor(df[i])
[1] FALSE

这与 R 有关还是我的 PC 有问题? 如果它与 R 有关,谁能解释发生了什么以及如何让我的循环运行?

您只需更改访问对象的方式。由于您使用的是数据框,因此您有两种选择来访问列

1.

i <- 1
is.factor(df[,i]) 

2.

i <- 1
is.factor(df[[i]])