Question

I would like to change this dataset

Date    A1  A2  A3  B1  B2  B3
1.4.04  5   1   2   10  13  4
2.4.04  2   2   0   11  12  5
3.4.04  4   4   3   14  15  8

to something like this

Date    A   B   C
1.4.04  5   10  1
1.4.04  1   13  2
1.4.04  2   4   3
2.4.04  2   11  1
2.4.04  2   12  2
2.4.04  0   5   3
3.4.04  4   14  1
3.4.04  4   15  2
3.4.04  3   8   3

Columns A1 to A3 are measurements from different stations and I want to put them in one column. The same for B. Column C will be the number of stations. How to do it in R?

Here is a reproducible example of the data.frame:

mydf <- structure(
  list(Date = structure(1:3, .Label = c("1.4.04", "2.4.04",  "3.4.04"), 
                        class = "factor"), 
       A1 = c(5L, 2L, 4L), A2 = c(1L,  2L, 4L), A3 = c(2L, 0L, 3L), 
       B1 = c(10L, 11L, 14L), B2 = c(13L,  12L, 15L), B3 = c(4L, 5L, 8L)), 
  .Names = c("Date", "A1", "A2",  "A3", "B1", "B2", "B3"), 
  row.names = c(NA, 3L), class = "data.frame")
Was it helpful?

Solution

This is a classic "wide" to "long" reshape problem (and your data--at least the sample data--are in a good form to do the conversion quite easily):

reshape(mydf, direction = "long", idvar="Date", 
        varying = 2:ncol(mydf), sep = "", timevar="C")
#            Date C A  B
# 1.4.04.1 1.4.04 1 5 10
# 2.4.04.1 2.4.04 1 2 11
# 3.4.04.1 3.4.04 1 4 14
# 1.4.04.2 1.4.04 2 1 13
# 2.4.04.2 2.4.04 2 2 12
# 3.4.04.2 3.4.04 2 4 15
# 1.4.04.3 1.4.04 3 2  4
# 2.4.04.3 2.4.04 3 0  5
# 3.4.04.3 3.4.04 3 3  8

OTHER TIPS

Does that work ? (replacing 'table' by the name of your dataset)

m1<-as.matrix(t(table[2:4]))
A<-as.vector(m1)
m2<-as.matrix(t(table[5:7]))
B<-as.vector(m2)

Date<-sort(rep(table$Date,3))
C<-rep(1:3,dim(table)[1])

output<-data.frame(Date,A,B,C)

If it doesn't, please provide reproducible example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top