使用动态名称进行因子转换

factor conversion using dynamic names

我目前动态访问 "two" 数据框的 "v" 列,我想将其转换为具有 "one" 数据框级别的因子。当我在 two[variable] 上使用 factor() 时,我目前正在获取 NA。知道如何让它工作吗?

one =data.frame(v=c("B","A"))
two = data.frame(v=c("A","B"))
variable = "v"
two[,variable] = factor(two[,variable] ,levels = one$v, ordered = TRUE)

   v
1 <NA>
2 <NA>

这里,'one'也是一个data.frame,所以我们需要从'one'

中提取对应的列
two[, variable] <- factor(two[,variable] ,levels = one[, variable], ordered = TRUE)
two[, variable]
#[1] A B
#Levels: B < A

如果它是 tibbletwo[, variable] 仍然是具有一列的 tibble。要将列提取为向量(因为 factor 方法适用于 vector),我们可以使用 $[[

two[[variable]] <- factor(two[[variable]], levels = one[[variable]], ordered = TRUE)

这也适用于 base R


注意:OP 首先展示了一个示例,其中 levels = one。现在,它更改为 one$v。如果在创建 'two' data.frame

后再次 运行 ,这将起作用