Arrays 基于向量的r子集数组
我觉得这个问题应该已经得到了回答,但我没有找到答案。我有一个数组,我想用一个向量来子集它。我知道怎么做很难,但我相信一定有一个简单的方法。有什么想法吗 下面是我的例子:Arrays 基于向量的r子集数组,arrays,r,subset,Arrays,R,Subset,我觉得这个问题应该已经得到了回答,但我没有找到答案。我有一个数组,我想用一个向量来子集它。我知道怎么做很难,但我相信一定有一个简单的方法。有什么想法吗 下面是我的例子: 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"], da
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
l[c("a", "a", "a")] # does not work
dat可以使用矩阵代替向量:
l[matrix(rep("a", 3), nrow=1)]
这已经得到了回答,但我想让事情变得更清楚一点。让我们以您为例:
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
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"
或者使用t(c(“a”、“a”、“a”))
# 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