为什么sapply返回需要转置的矩阵,然后转置的矩阵不会附加到数据帧? [英] Why does sapply return a matrix that I need to transpose, and then the transposed matrix will not attach to a dataframe?

查看:191
本文介绍了为什么sapply返回需要转置的矩阵,然后转置的矩阵不会附加到数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将会深入了解为什么会发生这种情况,以及我如何更雄心勃勃地这样做。

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)

get是:

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

谢谢! p>

Thanks!

推荐答案

扩展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

应用系列功能旨在用于向量和数组,因此您在使用data.frames(通常是向量列表)时需要注意。您可以使用以下事实:data.frames是您的优势列表,您可以使用 lapply

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆