简体   繁体   中英

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

一个带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:

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:

### 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 ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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