这已经得到了回答,但我想让事情更清楚一点。让我们在这里举个例子:
dat <- data.frame(a = rep(letters[1:3], 2), b = rep(letters[1:2], 3), c = c(rep("a",
5), "b"), x = rnorm(6), stringsAsFactors = FALSE)
l <- by(dat[, "x"], dat[, 1:3], mean)
l["a", "a", "a"] # works
## [1] 1.246
l[c("a", "a", "a")] # does not work
## [1] NA NA NA
建议在子集化中使用先前的答案matrix(rep("a", 3), nrow=1)
。我想详细说明为什么会这样。首先,我们来看看这两种数据结构的区别是什么:
a.mat <- matrix(rep("a", 3), nrow = 1)
a.vec <- c("a", "a", "a") # Note: this is equivalent to rep('a', 3)
a.mat
## [,1] [,2] [,3]
## [1,] "a" "a" "a"
a.vec
## [1] "a" "a" "a"
as.matrix(a.vec)
## [,1]
## [1,] "a"
## [2,] "a"
## [3,] "a"
l[a.mat]
## [1] 1.246
l[a.vec]
## [1] NA NA NA
l[as.matrix(a.vec)]
## [1] NA NA NA
a.mat
并且a.vec
当您将它们打印到屏幕时看起来相同,但它们的处理方式不同,因为 R 在列主要顺序中创建矩阵,因为它逐列写入和读取矩阵。当您使用矩阵进行子集化时,它将使用每一列作为不同的维度。如果矩阵中的列数与要子集化的对象中的维数匹配,它将使用每一列用于每个后续维度。
如果列数不匹配,R 会将矩阵折叠成向量并尝试以这种方式匹配元素索引。以下是更多示例:
a.mat[, -1] # Now only two columns
## [1] "a" "a"
l[a.mat[, -1]] # Notice you get NA twice here.
## [1] NA NA
l[matrix(rep("a", 4), nrow = 1)] # Using a matrix with 4 columns.
## [1] NA NA NA NA
作为旁注,当您使用字符向量进行子集化时,R 将尝试匹配任何元素名称。如果它们不存在,您将收到一个NA
或错误:
# Vector example:
x <- letters
x[1]
## [1] "a"
x["a"]
## [1] NA
names(x) <- letters
x[1]
## a
## "a"
x["a"]
## a
## "a"
x[c("a", "a", "a")]
## a a a
## "a" "a" "a"
x[a.mat] # collapsing matrix down to a vector.
## a a a
## "a" "a" "a"
# Matrix example:
x <- matrix(letters[1:9], nrow = 3, ncol = 3)
x
## [,1] [,2] [,3]
## [1,] "a" "d" "g"
## [2,] "b" "e" "h"
## [3,] "c" "f" "i"
x[c(1, 1)]
## [1] "a" "a"
x[1, 1]
## [1] "a"
x[c("a", "a")]
## [1] NA NA
x["a", "a"]
## Error: no 'dimnames' attribute for array
rownames(x) <- letters[1:3]
colnames(x) <- letters[1:3]
x
## a b c
## a "a" "d" "g"
## b "b" "e" "h"
## c "c" "f" "i"
x[c(1, 1)]
## [1] "a" "a"
x[1, 1]
## [1] "a"
x[c("a", "a")]
## [1] NA NA
x["a", "a"]
## [1] "a"
最后,如果您使用数字向量,您将始终得到一个定义的值(除非它超出范围):
l[c(1,1,1)]
## [1] 1.246 1.246 1.246
l[1, 1, 1]
## [1] 1.246