Question

Very often I've data in a "wide format" with several columns for the same variable (see here) and I would like to have my data in a long format (see here). Do you have any simple and safe solution ?

Was it helpful?

Solution

As your 2 examples doesn't have same numbers, don't know if this is what you want:

data <- read.table(text='"id","name1","name2","x1","x2"
1,"Mr a","Mr c","0.575710014459387","-0.991747242336918"
2,"Mr b","Mr d","-0.126033858727122","0.854792650572792"', sep=',', header=TRUE)

reshape(data, direction = 'long', idvar = 'id', varying = list(c('x1', 'x2'), c('name1', 'name2')), times=c('a', 'b'))

OTHER TIPS

Or with the melt function to unpivot:

library(reshape2)
data <- read.table(text='"id","name1","name2","x1","x2","Mr a","Mr c","0.575710014459387","-0.991747242336918","Mr b","Mr d","-0.126033858727122","0.854792650572792"', sep=',', header=TRUE)
reshape(data, direction = 'long', idvar = 'id', varying = list(c('x1', 'x2'), c('name1', 'name2')), times=c('a', 'b'))
melt(data,c("id","name1","name2"),variable.name="x",value.name="value")
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top