3

我觉得这个问题应该已经回答了,但我没有找到。我有一个数组,我想使用向量对其进行子集化。我知道如何以艰难的方式做到这一点,但我确信必须有一个简单的方法。有任何想法吗?

这是我的例子:

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.

4

2 回答 2

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.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 
于 2013-09-21T21:43:02.700 回答
3

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

l[matrix(rep("a", 3), nrow=1)]
于 2013-09-21T20:01:53.043 回答