简体   繁体   English

在R中重塑数据

[英]Reshaping data in R

I want to reshape a dataframe and I am struggling with the documentation for the reshape and stack functions. 我想重塑一个数据框,我正在努力处理重塑和堆栈函数的文档。 My data frame is like this: 我的数据框是这样的:

x<-rnorm(n=20, mean=0, sd=1)
y<-rnorm(n=20, mean=10, sd=1)
fact<-rep(1:5, times=4)
df<-data.frame(x,y,fact)

In the end I want a 2 column dataframe (40x2) one column with x and y 'stacked' and one column with the corresponding x&y's factor 最后我想要一个2列数据帧(40x2),一列用x和y'堆叠',一列用相应的x和y因子

一个带melt衬里

reshape2::melt(df, id = 'fact', variable.name = 'xy')

I am not sure if you wanted to retain the information about where the values came from (ie the x or y columns. If you do not then this is easy: 我不确定您是否要保留有关值来自何处的信息(即x或y列。如果不这样,那么这很容易:

df2 <- data.frame(xy = c(df$x,df$y), fact=c(df$fact, df$fact))

If you want to keep the information in fact then one of these: 如果你想保持在信息fact然后其中之一:

### Method 1
df2 <- data.frame(xy = c(df$x,df$y), 
                  fact=c(paste("x", df$fact, sep="."), paste("y", df$fact, sep=".") )
                  )
str(df2 )
'data.frame':   40 obs. of  2 variables:
 $ xy  : num  1.58043 -0.00399 0.84784 -0.10012 -0.27963 ...
 $ fact: Factor w/ 10 levels "x.1","x.2","x.3",..: 1 2 3 4 5 1 2 3 4 5 ...

### Method 2
 df2 <- stack(df[, 1:2])
 df2$fact=df$fact
 str(df2)
'data.frame':   40 obs. of  3 variables:
 $ values: num  1.58043 -0.00399 0.84784 -0.10012 -0.27963 ...
 $ ind   : Factor w/ 2 levels "x","y": 1 1 1 1 1 1 1 1 1 1 ...
 $ fact  : int  1 2 3 4 5 1 2 3 4 5 ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM