Reorder data for ANOVA

I didn't quite hug R and how to change the data. I have an old SPSS data file that needs reordering, so I can do ANOVA in R.

My current data file has the following format:

ONE <- matrix(c(1, 2, 777.75, 609.30, 700.50, 623.45, 701.50, 629.95, 820.06, 651.95,"nofear","nofear"), nr=2,dimnames=list(c("1", "2"), c("SUBJECT","AAYY", "BBYY", "AAZZ", "BBZZ", "XX"))) 

And I need to change it to this:

 TWO <- matrix(c(1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 777.75, 701.5, 700.5, 820.06, 609.3, 629.95, 623.95, 651.95), nr=8, dimnames=list(c("1", "1", "1", "1", "2", "2", "2", "2"), c("SUBJECT","AA", "ZZ", "XX", "RT"))) 

I am sure there is an easy way to do this, rather than manual coding. Thanks for attention.

+4
source share
2 answers

That should do it. You can change it a bit, but this is an idea:

 library(reshape) THREE <- melt(as.data.frame(ONE),id=c("SUBJECT","XX")) THREE$AA <- grepl("AA",THREE$variable) THREE$ZZ <- grepl("ZZ",THREE$variable) THREE$variable <- NULL # cleanup THREE$XX <- as.factor(THREE$XX) THREE$AA <- as.numeric(THREE$AA) THREE$ZZ <- as.numeric(THREE$ZZ) 
+9
source

Reshape and reshape () help to deal with similar things, but in this simple case, when you have to generate variables manually, it’s quite simple, just use automatic replication in R.

 TWO <- data.frame(SUBJECT = rep(1:2,each = 4), AA = rep(1:0, each = 2), ZZ = 0:1, XX = 1, RT = as.numeric(t(ONE[,2:5]))) 

This gives you the TWO that you asked for, but it does not generalize to more ONE easily. I think it makes sense

 n <- nrow(ONE) TWO <- data.frame(SUBJECT = rep(ONE$SUBJECT, 4), AB = rep(1:0, each = n), YZ = rep(0:1, each = 2*n), fear = ONE$XX, RT = unlist(ONE[,2:5])) 

This last one gives more representative variable names and handles the probable case when your data is actually much more than XX (fear), different and more objects. Also, given that you are reading it from an SPSS data file, then ONE is actually a data frame with numeric numbers and factorized character columns. Reorganization was just that part of the code ...

 TWO <- data.frame(SUBJECT = rep(ONE$SUBJECT, 4), fear = ONE$XX, RT = unlist(ONE[,2:5])) 

After that you can add other variables.

+3
source

All Articles