2012-08-09 73 views
1

我在R中有下表,我想转置它。我是R新手,一直在使用SAS。R(... ala SAS PROC转置)重塑

所以我想有一个proc转置的副本是SAS。我也以我想要的格式给出输出。

C_number<-c(1:20) 
REG<-letters[1:20] 
Market<-c(21:40) 
DF<-data.frame(C_number,REG,Market) 
n <- nrow(DF) 
DF$A_count <- sample(100, n, replace=TRUE) 
DF$B_count <- sample(100, n, replace=TRUE) 

输出应该是:

C_number   REG  Market  Name of former variable   Mem_count1 
1     A  21   A_count       5 
1     A  21   B_count       80 
2     B  22   A_count       36 
2     B  22   B_count       56 
3     C  23   A_count       77 
3     C  23   B_count       26 

因此,转背后的基本思想是两列A_COUNT & B_count转换成一个命名为“前变量名”,并创建一个新的列mem_count1,它会给出相应的值。

它不完全是转置,但有点类似。我不知道如何做到这一点。请帮我解决这个问题。

+2

尽管问不同;这是非常接近http://stackoverflow.com/questions/9586636/matrix-stacking-with-column-name-in-r。另外,正如原文所述,不完全是一个转置,我们能否构成一个更好的术语,因为转置具有非常明确的意义?也许在R中合并,堆栈,重塑或变换列? – Thell 2012-08-09 17:58:23

回答

6

您可以使用reshape2(或reshape包),特别是melt函数。 使用像你这样的数据集(不一样的,因为不同的随机种子的),我们可以像这样:

require(reshape2) 
DF_result <- melt(DF, measure.vars = c("A_count", "B_count")) 
head(DF_result) 


## C_number REG Market variable value 
## 1  1 a  21 A_count 49 
## 2  2 b  22 A_count 99 
## 3  3 c  23 A_count 19 
## 4  4 d  24 A_count 43 
## 5  5 e  25 A_count 53 
## 6  6 f  26 A_count 50 
0

这将基本功能reshape做到这一点:

reshape(DF, 
     direction="long", 
     idvar=1:3, varying=c("A_count","B_count"), # the constant and varying columns 
     times=c("A_count","B_count"),  # sets the values for new 'source' column 
     v.names="Name_of_former_variable") # the header for the 'source' column 

       C_number REG Market time Counts 
1.a.21.A_count   1 a  21 A_count  14 
2.b.22.A_count   2 b  22 A_count  18 
3.c.23.A_count   3 c  23 A_count  49 
4.d.24.A_count   4 d  24 A_count  64 
5.e.25.A_count   5 e  25 A_count  99 
6.f.26.A_count   6 f  26 A_count  10 
7.g.27.A_count   7 g  27 A_count  70 
8.h.28.A_count   8 h  28 A_count  1 
snipped output