为什么 sapply 返回一个我需要转置的矩阵,然后转置的矩阵不会附加到数据帧? [英] Why does sapply return a matrix that I need to transpose, and then the transposed matrix will not attach to a dataframe?
问题描述
如果您能深入了解为什么会发生这种情况,以及我如何能更有说服力地做到这一点,我将不胜感激.
I would appreciate insight into why this happens and how I might do this more eloquently.
当我使用 sapply 时,我希望它返回一个 3x2 矩阵,但它返回一个 2x3 矩阵.为什么是这样?为什么很难将它附加到另一个数据框?
When I use sapply, I would like it to return a 3x2 matrix, but it returns a 2x3 matrix. Why is this? And why is it difficult to attach this to another data frame?
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
虽然以下似乎给出了预期的结果:
although the following appears to give the desired result:
rownames(out) <- c('col1', 'col2')
b <- cbind(b, t(out))
我无法对变量进行操作:
I can not operate on the variables:
b$var1/b$var2
返回
Error in b$var1/b$var2 : non-numeric argument to binary operator
谢谢!
推荐答案
扩展 DWin 的答案:查看 out
对象的结构会有所帮助.它解释了为什么 b$var1/b$var2
没有达到您的预期.
To expand on DWin's answer: it would help to look at the structure of your out
object. It explains why b$var1/b$var2
doesn't do what you expect.
> 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 是列表这一事实.
The apply
family of functions are designed to work on vectors and arrays, so you need to take care when using them with data.frames (which are usually lists of vectors). You can use the fact that data.frames are lists to your advantage with lapply
.
> 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
这篇关于为什么 sapply 返回一个我需要转置的矩阵,然后转置的矩阵不会附加到数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!