[R] reversed variables in stats::reshape()

arun smartpink111 at yahoo.com
Sat Jan 25 01:28:33 CET 2014


Hi,

You can change varying1 to:

varying1 = list(seq(3,ncol(data1),2), seq(4,ncol(data1),2))#and then try it on your code
test = reshape(
        data = data1,
        direction = "long",
        idvar = c("Participant","Treatment"),
        v.names = c("R","L"),
    times= seq(2, 30, by = 2),
        timevar = "Time",
        varying = varying1)


A.K.


Dear R-Help readers, 

I am writing to ask about some behavior by stats::reshape() that surprised 
me. In the example below, I expected the values of variables "R" and "L" in 
data.frame "test" to be the reverse of what they are - ie I expected that 
test$R = seq(1:29, by =2) and test$L = seq(2:30, by = 2). 

data1 = data.frame( 
        check.names = F, 
        Participant = 1, 
        Treatment = "A", "2 min R" = 1L, 
        "2 min L" = 2L, "4 min R" = 3L, "4 min L" = 4L, "6 min R" = 5L, 
        "6 min L" = 6L, "8 min R" = 7L, "8 min L" = 8L, "10 min R" = 9L, 
        "10 min L" = 10L, "12 min R" = 11L, "12 min L" = 12L, "14 min R" = 
13L, 
        "14 min L" = 14L, "16 min R" = 15L, "16 min L" = 16L, "18 min R" = 
17L, 
        "18 min L" = 18L, "20 min R" = 19L, "20 min L" = 20L, "22 min R" = 
21L, 
        "22 min L" = 22L, "24 min R" = 23L, "24 min L" = 24L, "26 min R" = 
25L, 
        "26 min L" = 26L, "28 min R" = 27L, "28 min L" = 28L, "30 min R" = 
29L, 
        "30 min L" = 30L) 

varying1 = colnames(data1)[3:32] 

test = reshape( 
        data = data1, 
        direction = "long", 
        idvar = c("Participant","Treatment"), 
        v.names = (c("R","L")), 
        timevar = "Time", 
        times = seq(2, 30, by = 2), 
        varying = varying1) 

test 

[ end code] 

I looked into the definition of reshape, and found the following line: 

varying <- split(varying, rep(v.names, ntimes)) 

The following edit seems to produce the behavior I expected: 

varying <- split(varying, rep(v.names, ntimes))[v.names] 

However, I strongly suspect I am making a mistake; I'd be grateful if 
someone would help me find it. 

Here is the output of  sessionInfo(): 

R version 3.0.2 (2013-09-25) 
Platform: x86_64-apple-darwin10.8.0 (64-bit) 

locale: 
[1] C 

attached base packages: 
[1] graphics  datasets  stats     utils     grDevices methods   base 

other attached packages: 
[1] rj_1.1.3-1 

loaded via a namespace (and not attached): 
[1] rj.gd_1.1.3-1 tools_3.0.2 

Thanks, 
Doug 





More information about the R-help mailing list