对R中的二维因子感到困惑

问题描述 投票:2回答:1

我有以下数据框:

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))

我现在想获得7至14个选定玩具的所有玩具组合。在此线程(Unordered combinations in R)之后,我正在使用combinations包中的arrangements函数:

library(arrangements)
combs <- lapply(7:14, combinations, x = dat$toys)

str(combs)查看结果,它给出了一个长度为8的列表,其中每个列表元素都是二维因子,例如

test <- combs[[1]]
dim(test)

但是,如果我现在想将列表元素转换为数据框,它只为我提供一列的数据框,而我希望as.data.frame(combs[[1]])为7列。

如果我在上面的组合函数中使用整数或字符向量,则所有操作都将按预期进行,例如与:

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]])

我得到了一个包含几列的正确数据框。

为什么我的代码不能使用整数和字符,而不能使用因子?

r list r-factor
1个回答
0
投票

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

我们可以在R中尝试使用字符和整数(如您所示):

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

但是,将其转换为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

我的猜测是,您很幸运使用7到14的组合。如果尝试使用较小的数字,它将失败:

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
© www.soinside.com 2019 - 2024. All rights reserved.