当 data.frame 中的列数可以减少到 1 时,防止转换为因子

Prevent conversion to factor when number of columns in a data.frame can be reduced to one

提问人:bli 提问时间:11/29/2016 最后编辑:Communitybli 更新时间:11/29/2016 访问量:171

问:

我有一个过程,可以根据列上的条件列表从数据帧中提取项目(请参阅使用作为 (column_name = 值) 列表给出的条件从 R 数据帧中提取项目):

以下是数据框和条件列表:

> experimental_plan_1
  lib genotype treatment replicate
1   A       WT    normal         1
2   B       WT       hot         1
3   C      mut    normal         1
4   D      mut       hot         1
5   E       WT    normal         2
6   F       WT       hot         2
7   G      mut    normal         2
8   H      mut       hot         2
> condition_1 <- list(genotype="WT", treatment="normal")

我的目标是提取与列表中给定的条件相对应的行的列中的值。lib

我可以使用以下函数来提取所需的值:

> get_libs <- function(experimental_plan, condition) {experimental_plan[apply((experimental_plan[, names(condition)] == condition), 1, all), "lib"]}

这适用于上述数据框:

> get_libs(experimental_plan_1, condition_1)
[1] A E
Levels: A B C D E F G H

但是,我希望这更笼统:My 和 可以有不同的列:experimental_plancondition

> experimental_plan_2
  lib genotype replicate
1   A       WT         1
2   B       WT         2
3   C       WT         3
4   D      mut         1
5   E      mut         2
6   F      mut         3
> condition_2 <- list(genotype="WT")

这次失败了:

> get_libs(experimental_plan_2, condition_2)
Error in apply((experimental_plan[, names(condition)] == condition), 1,  : 
  dim(X) must have a positive length

在这种情况下,预期输出应为:

[1] A B C
Levels: A B C D E F

如何编写一个以更健壮的方式执行相同操作的函数?


评论

我发现非常令人沮丧的是,尽管这两种情况都非常相似,但该函数不起作用:两个数据框都有一个列,并且在这两种情况下,条件列表中的名称都与数据框中的列名称相对应。lib

当从数据帧中提取的列数减少到 1 时,R 显然会自动将 data.frame 转换为因子:

> class(experimental_plan_1)
[1] "data.frame"
> class(experimental_plan_2)
[1] "data.frame"
> class(names(condition_1))
[1] "character"
> class(names(condition_2))
[1] "character"
> class(experimental_plan_1[, names(condition_1)])
[1] "data.frame"
> class(experimental_plan_2[, names(condition_2)])
[1] "factor"

这违背了最小意外原则。 我希望在给出相同类型的输入时,计算将返回相同类型的输出。

R Vector DataFrame 最小惊奇

评论


答: 暂无答案