0

I need to convert my dataset from wide to long format. I have used the reshape function pretty frequently and this is my first problem with it. I think it's because one variable has a value of 0 for all of time 1. This is the main part of my code:

c1dat0_long <- reshape(widedata, 
    varying = c("ATT0", "ATT1", "ATT2", "ATT3", "ATT4",
                "ATP0", "ATP1", "ATP2", "ATP3", "ATP4",
                "n_ATT0", "n_ATT1", "n_ATT2", "n_ATT3", "n_ATT4",
                "cm_ATP0", "cm_ATP1", "cm_ATP2", "cm_ATP3", "cm_ATP4",
                "sd_ATP0", "sd_ATP1", "sd_ATP2", "sd_ATP3", "cm_ATP4",
                "n_NEW0", "n_NEW1", "n_NEW2", "n_NEW3", "n_NEW4",
                "cm_AGE0", "cm_AGE1", "cm_AGE2", "cm_AGE3", "cm_AGE4",
                "p_FEMALE0", "p_FEMALE1", "p_FEMALE2", "p_FEMALE3", "p_FEMALE4",
                "n_FEMALE0", "n_FEMALE1", "n_FEMALE2", "n_FEMALE3", "n_FEMALE4"),
    idvar = "ID", sep="", timevar = "TIME", direction = "long")

I think the problem is that the value of n_NEW0 is 0 for all subjects. It needs to be because everyone is new at time 1, so it has to be the same number. If I just used the number of people in the group then it would look like each group had a different number of "new" participants at time 1.

This is what I got:

Error in reshapeLong(data, idvar = idvar, timevar = timevar, varying = varying, :
'varying' arguments must be the same length

Is there anything I can do to make this work? I've tried using tidyr::pivot_longer instead but it hasn't worked and I can't seem to figure out where I'm going wrong there either.

PS. I just tried changing the values of n_NEW0 to vary and I'm getting the same error message so maybe I was wrong about the root of the problem.

ACK3
  • 1
  • 2
  • `reshape` may not be the best tool for reshaping data (it is showing its age). Depending on your needs, you might prefer to use `tidyr::pivot_*` or `reshape2::melt`/`::dcast`. Unless you're looking for other than I'm thinking, see https://stackoverflow.com/q/11608167/3358272 for "long to wide", and https://stackoverflow.com/q/2185252/3358272, https://stackoverflow.com/q/68058000/3358272 for "wide to long" reshaping. – r2evans May 03 '23 at 21:01
  • I can't seem to get tidyr::pivot_longer to work for 80 time-varying variables. I'm not sure what I'm doing wrong but it seems to only want one variable. – ACK3 May 03 '23 at 21:23
  • Can you share a subset of data or an example similar to it? e.g. if you run `dput(widedata[1:5, 1:10])` that will create code so we can replicate your first 5 rows and 10 columns in the same structure & formats you have them. That way people can test out if a potential solution works. – Jon Spring May 03 '23 at 21:29
  • 2
    You've got a typo in your `varying=` argument - instead of `sd_ATP4` you repeat `cm_ATP4`, making the sets of variables unbalanced. – thelatemail May 03 '23 at 21:31

0 Answers0