转置矩阵 R [英] transpose matrix R

查看:56
本文介绍了转置矩阵 R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 R 中有一个数据框,我想将其转置为不同的格式,请参见下面的示例:我可以在 R 中使用转置函数吗?

I have a data frame in R that I want to transpose into a different format, please see the example below: Can I use the transpose function in R?

输入数据框:

Samples          A1    A2      A3     B1     B2       B3

Sample1         123    123     321    32     321       32132 
Sample2         12321  32321   2321   2313   3213      3123  
Sample3         454    54      543    543    43        435

期望的输出:

Samples           1      2       3    

Sample1   A       123    123     321     
Sample1   B       32     321     32132
Sample2   A       12321  32321   2321     
Sample2   B       2313   3213    3123
Sample3   A       454    54      543
Sample3   B       543    43      435

推荐答案

要为基础 R 提供一些道具,请查看 reshape() 函数.假设您的 data.frame 被称为mydf",请尝试:

To give some props to base R, look at the reshape() function. Assuming your data.frame is called "mydf", try:

reshape(mydf, direction = "long", 
        idvar="Samples", varying=2:ncol(mydf), 
        v.names=c("1", "2", "3"), times = c("A", "B"))
          Samples time     1     2     3
Sample1.A Sample1    A   123   123   321
Sample2.A Sample2    A 12321 32321  2321
Sample3.A Sample3    A   454    54   543
Sample1.B Sample1    B    32   321 32132
Sample2.B Sample2    B  2313  3213  3123
Sample3.B Sample3    B   543    43   435

这篇关于转置矩阵 R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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