Reputation: 43
How to melt single column from T1 to T2.
T1
Mar-17 T2
328 Mar-17 328
29.57 Mar-17 29.57
38.483 Mar-17 38.483
31.26 Mar-17 31.26
37.3 Mar-17 37.3
60.026 Mar-17 60.026
47.059 Mar-17 47.059
40.215 Mar-17 40.215
51.79 Mar-17 51.79
45.284 Mar-17 45.284
41.271 Mar-17 41.271
42.411 Mar-17 42.411
T3
Mar-17 Apr-17 T4
328 396 Mar-17 328
29.57 216.57 Mar-17 29.57
38.483 116.483 Mar-17 38.483
31.26 168.26 Mar-17 31.26
37.3 128.3 Mar-17 37.3
60.026 82.026 Mar-17 60.026
47.059 113.059 Mar-17 47.059
40.215 165.215 Mar-17 40.215
51.79 80.79 Mar-17 51.79
45.284 185.284 Mar-17 45.284
41.271 183.271 Mar-17 41.271
42.411 204.411 Mar-17 42.411
Apr-17 396
Apr-17 216.57
Apr-17 116.483
Apr-17 168.26
Apr-17 128.3
Apr-17 82.026
Apr-17 113.059
Apr-17 165.215
Apr-17 80.79
Apr-17 185.284
Apr-17 183.271
Apr-17 204.411
When I am using stack
T2 <- stack(T1)
it is giving error message
Error in rep.int(names(x), lengths(x)) : invalid 'times' value
Upvotes: 0
Views: 129
Reputation: 14360
I'm able to reproduce your error when I do not have column names (but rather have Mar-17
and Apr-17
as the first observation) so I am assuming that this is how your data is structured. If Mar-17
and Apr-17
are your column names, stack()
should work.
In this case, you could set your variable names to be the values in the first row and then use stack()
on everything excluding the first row:
names(T1) <- T1[1,]
T2 <- stack(T1[-1, , drop = F])
head(T2)
# values ind
#1 328 Mar-17
#2 29.57 Mar-17
#3 38.483 Mar-17
#4 31.26 Mar-17
#5 37.3 Mar-17
#6 60.026 Mar-17
names(T3) <- T3[1,]
T4 <- stack(T3[-1,])
head(T4)
# values ind
#1 328 Mar-17
#2 29.57 Mar-17
#3 38.483 Mar-17
#4 31.26 Mar-17
#5 37.3 Mar-17
#6 60.026 Mar-17
Data:
T1 <- structure(list(c("Mar-17", "328", "29.57", "38.483", "31.26",
"37.3", "60.026", "47.059", "40.215", "51.79", "45.284", "41.271",
"42.411")), class = "data.frame", row.names = c(NA, -13L))
T3 <- structure(list(c("Mar-17", "328", "29.57", "38.483", "31.26",
"37.3", "60.026", "47.059", "40.215", "51.79", "45.284", "41.271",
"42.411"), c("Apr-17", "396", "216.57", "116.483", "168.26",
"128.3", "82.026", "113.059", "165.215", "80.79", "185.284",
"183.271", "204.411")), row.names = c(NA, -13L), class = "data.frame")
Upvotes: 2