关于R中二维因子的困惑

关于R中二维因子的困惑,r,list,r-factor,R,List,R Factor,我有以下数据框: dat <- data.frame(toys = c("yoyo", "doll", "duckie", "tractor", "airplaine", "ball", "racecar", "dog", "jumprope", "car", "elephant", "bear", "xylophone", "tank", "checkers", "boat", "train", "jacks", "truck", "whistle", "pinwheel"),

我有以下数据框:

dat <- data.frame(toys = c("yoyo", "doll", "duckie", "tractor", "airplaine", "ball", "racecar", "dog", "jumprope", "car", "elephant", "bear", "xylophone", "tank", "checkers", "boat", "train", "jacks", "truck", "whistle", "pinwheel"),
                  price = c(1.22, 2.75, 1.85, 5.97, 6.47, 2.16, 7.13, 4.57, 1.46, 5.18, 3.16, 4.89, 7.11, 6.45, 4.77, 8.04, 6.71, 2.31, 6.21, 0.98, 0.87))
使用
str(combs)
查看结果,它给出了一个长度为8的列表,其中每个列表元素都是一个二维因子,例如

test <- combs[[1]]
dim(test)
我得到了一个包含多个列的适当数据帧


为什么我的代码只处理整数和字符,而不处理因子?

当调用组合时,底层会在输出上设置dim属性。如果是字符、数字或整数,则会将其转换为矩阵,然后您可以从中获取data.frame:

对于字符和整数,我们可以在R中尝试此操作(如您所示):

但是,将其转换为data.frame失败:

as.data.frame(x)
   x.1  x.2
1    1    3
2    2    4
3 <NA> <NA>
4 <NA> <NA>
Warning message:
In format.data.frame(if (omit) x[seq_len(n0), , drop = FALSE] else x,  :
  corrupt data frame: columns will be truncated or padded with NAs

如何将列表元素转换为数据帧?它是如何像预期的那样使用字符或整数向量的?我在上面调整了我的帖子。我尝试了上面的代码,但无法复制结果
as.data.frame(combs[[1]])
返回了一个七列数据帧。为了澄清,这是针对factor的,而不是string/int的。您确定吗?我只是重试了一下,再次得到了一个包含813960行的factor案例的单列数据帧。(我刚刚编辑了我的帖子,使示例不那么模棱两可,即,我将对象名称改为combs/combs2/combs3。谢谢你的解释。从你的角度来看,这种行为是故意的还是一个bug?你知道如何使用因子得到数据帧结果吗?@deschen,我认为它不是针对因子的。它不是有一个因子矩阵是有意义的。因为对于所有行和列函数,都需要继承一个完整级别的矩阵。这对您有什么帮助?如果您真的想要一个因子的data.frame,您需要首先获得字符,然后遍历每一列,使其成为具有原始级别的因子
combs2 <- lapply(7:14, combinations, x = as.character(dat$toys)) # or
combs3 <- lapply(7:14, combinations, x = 1:21)

test2 <- as.data.frame(combs2[[1]])
test3 <- as.data.frame(combs3[[1]])
x = 1:4
attr(x,"dim") <- c(2,2)
class(x)
[1] "matrix"
dim(data.frame(x))
1] 2 2

x = as.character(1:4)
attr(x,"dim") <- c(2,2)
class(x)
[1] "matrix"
dim(data.frame(x))
[1] 2 2
x = factor(1:4)
attr(x,"dim") <- c(2,2)
class(x)
[1] "factor"
str(x)
Factor[1:2, 1:2] w/ 4 levels "1","2","3","4": 1 2 3 4
x
     [,1] [,2]
[1,] 1    3   
[2,] 2    4   
Levels: 1 2 3 4
as.data.frame(x)
   x.1  x.2
1    1    3
2    2    4
3 <NA> <NA>
4 <NA> <NA>
Warning message:
In format.data.frame(if (omit) x[seq_len(n0), , drop = FALSE] else x,  :
  corrupt data frame: columns will be truncated or padded with NAs
data.frame(combinations(dat$toys,5))
Error in `[.default`(xj, i, , drop = FALSE) : subscript out of bounds
data.frame(combinations(dat$toys,2))
#throws same erros as above