r子集数组使用向量

时间:2013-09-21 19:42:18

标签: 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"], dat[ , 1:3], mean)

l["a", "a", "a"] # works  
l[c("a", "a", "a")] # does not work

所以我想我需要一种方法来删除c()包装器格式c("a", "a", "a"),然后再将其传递给l

2 个答案:

答案 0 :(得分:4)

这已经得到了解答,但我想让事情变得更加清晰。我们来这里举个例子:

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.mata.vec看起来一样,但它们不是 以相同的方式处理,因为R在Column Major Order中创建矩阵,因为它逐列写入和读取矩阵。当您使用矩阵进行子集化时,它会将每列用作不同的维度。如果矩阵中的列数与要进行子集化的对象中的维数相匹配,则每个后续维度都将使用每列。

如果列数不匹配,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 

答案 1 :(得分:3)

您可以使用矩阵代替矢量:

l[matrix(rep("a", 3), nrow=1)]