You could convert your data from a wide format to a long format using the reshape function in base R:

DF2 <- reshape(DF, direction="long",
        idvar=names(DF)[1:3],
        varying=c("site1_elev", "site1_temp", "site2_elev", "site2_temp"),
        v.names=c("elev", "temp"),
        times=1:2,
        timevar = "siteID")

rownames(DF2) <- NULL
DF2

  year month day siteID elev temp
1 2000     5   6      1 1300   20
2 2000     5   7      1 1300   21
3 2000     5   8      1 1300   19
4 2000     5   9      1 1300   22
5 2000     5   6      2 1500   21
6 2000     5   7      2 1500   22
7 2000     5   8      2 1500   20
8 2000     5   9      2 1500   23

Philip


On 23/10/2016 4:50 AM, lily li wrote:
Hi R users,

I want to melt a dataframe, but it mixed up the variables.

DF is the original dataset:
year  month  day  site1_elev  site2_elev  site1_temp  site2_temp
2000     5        6        1300          1500            20              21

2000     5        7        1300          1500            21              22
2000     5        8        1300          1500            19              20
2000     5        9        1300          1500            22              23

How to melt the dataframe and get the following dataset? Thanks for your
help.

year  month  day  siteID   elev   temp
2000    5         6       1      1300    20
2000    5         6       2      1500    21
2000    5         7       1      1300    21
2000    5         7       2      1500    22

        [[alternative HTML version deleted]]

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

______________________________________________
R-help@r-project.org mailing list -- To UNSUBSCRIBE and more, see
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to