0

I have the following format of the data:

    m1   m2   m3 names
1 24.5 28.4 26.1     1
2 23.5 34.2 28.3     2
3 26.4 29.5 24.3     3
4 27.1 32.2 26.2     4
5 29.9 20.1 27.8     5

How can I prepare this data to the format that I can feed to aov in R?

I.e.

   values ind name 
1    24.5  m1 1
2    23.5  m1 2
3    26.4  m1 3
...

For one way anova I just used stack command. How can I do it for two way anova, without having a loop?

Sergey Ivanov
  • 3,719
  • 7
  • 34
  • 59

3 Answers3

1

Try this

library(reshape2) 
melt(df)
user2100721
  • 3,557
  • 2
  • 20
  • 29
1

user2100721 has given an answer using a package. Without package imports this can be solved as

a <- read.table(header=TRUE, text="m1   m2   m3 names
                                  24.5 28.4 26.1     1
                                  23.5 34.2 28.3     2
                                  26.4 29.5 24.3     3
                                  27.1 32.2 26.2     4
                                  29.9 20.1 27.8     5")

reshape(a, direction="long", varying=list(c("m1","m2","m3")))
Bernhard
  • 4,272
  • 1
  • 13
  • 23
1

An alternative to all above answers which are nice, you can use gather from tidyr package. Gather takes multiple columns and collapses them into key-value pairs. You need to pass two variables to it, one is the key and the other is value

X<- structure(list(m1 = c(24.5, 23.5, 26.4, 27.1, 29.9), m2 = c(28.4, 
    34.2, 29.5, 32.2, 20.1), m3 = c(26.1, 28.3, 24.3, 26.2, 27.8), 
        names = 1:5), .Names = c("m1", "m2", "m3", "names"), class = "data.frame", row.names = c(NA, 
    -5L))


library(tidyr)
dat <- X %>% gather(variable, value)

> head(dat,10)
#   variable value
#1        m1  24.5
#2        m1  23.5
#3        m1  26.4
#4        m1  27.1
#5        m1  29.9
#6        m2  28.4
#7        m2  34.2
#8        m2  29.5
#9        m2  32.2
#10       m2  20.1