r - 为什么sapply返回需要转置的矩阵,然后转置的矩阵将不会附加到数据帧?

标签 r data-structures vectorization apply

我希望能深入了解为什么会发生这种情况,以及我将如何 Eloquent 地做到这一点。

当我使用sapply时,我希望它返回一个3x2矩阵,但它返回一个2x3矩阵。为什么是这样?为何很难将其附加到另一个数据框?

a <- data.frame(id=c('a','b','c'), var1 = c(1,2,3), var2 = c(3,2,1))
out <- sapply(a$id, function(x) out = a[x, c('var1', 'var2')])
#out is 3x2, but I would like it to be 2x3
#I then want to append t(out) (out as a 2x3 matrix) to b, a 1x3 dataframe
b <- data.frame(var3=c(0,0,0))

当我尝试附加这些时,
b[,c('col2','col3')] <- t(out)

我得到的错误是:
Warning message:
In `[<-.data.frame`(`*tmp*`, , c("col2", "col3"), value = list(1,  :
  provided 6 variables to replace 2 variables

尽管以下内容似乎可以达到预期的效果:
rownames(out) <- c('col1', 'col2')
b <- cbind(b, t(out))

我无法对变量进行操作:
b$var1/b$var2

退货
Error in b$var1/b$var2 : non-numeric argument to binary operator

谢谢!

最佳答案

扩展DWin的答案:这将有助于查看out对象的结构。它解释了为什么b$var1/b$var2不能达到您的期望。

> out <- sapply(a$id, function(x) out = a[x, c('var1', 'var2')])
> str(out)  # this isn't a data.frame or a matrix...
List of 6
 $ : num 1
 $ : num 3
 $ : num 2
 $ : num 2
 $ : num 3
 $ : num 1
 - attr(*, "dim")= int [1:2] 2 3
 - attr(*, "dimnames")=List of 2
  ..$ : chr [1:2] "var1" "var2"
  ..$ : NULL
apply系列函数旨在用于向量和数组,因此在将它们与data.frames(通常是向量列表)一起使用时,需要格外小心。您可以使用lapply来利用data.frames是列表的事实。
> out <- lapply(a$id, function(x) a[x, c('var1', 'var2')])  # list of data.frames
> out <- do.call(rbind, out) # data.frame
> b <- cbind(b,out)
> str(b)
'data.frame':   3 obs. of  4 variables:
 $ var3: num  0 0 0
 $ var1: num  1 2 3
 $ var2: num  3 2 1
 $ var3: num  0 0 0
> b$var1/b$var2
[1] 0.3333333 1.0000000 3.0000000

关于r - 为什么sapply返回需要转置的矩阵,然后转置的矩阵将不会附加到数据帧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4140371/

相关文章:

r - 使用矩阵指定的 data.table 列值的平均值

algorithm - 具有 N 个节点且具有相同后序和中序遍历的二叉树的数目

算法/数据结构设计面试题

python - 如何有效地连接 numpy 中的许多 arange 调用?

matlab - 有没有办法避免循环使这段代码更快?

r - 我在 data.table 中复制行的方法有效吗?

windows - 错误 : C stack usage is too close to the limit in Windows environment

ruby 性能 : Multi-key hashes

python - 为 pandas 数据框列向量化 HumanName 库

r - 在带有 NLME 对象和公式的函数调用中使用 predict