I have an example dataset "dfsales" in a wide format and now I am trying to change it into a long format. I went through a lot of examples with single set of values (e.g just having month1:month7). But I need to work with a lot of column set (e.g month1:month7, goods1:goods7, built1-built7, condition1-condition7 etc). Here in this example I have just added 2 set (month1:month7 and goods1:goods7).
dfsales <- data.frame(
subjectid = c("a","b","c","d","e","f","g","h","i","j","k"),
location = c("NY","NC","WA","WA","OR","CA","AR","KS","AZ","VT","MA"),
month1 = c(NA,NA,1,0,0,2,1,1,0,0,0),
month2 = c(NA,NA,0,0,0,0,NA,0,0,0,NA),
month3 = c(NA,1,0,1,0,0,0,1,NA,NA,NA),
month4 = c(0,0,0,0,0,1,2,0,1,NA,0),
month5 = c(NA,NA,NA,NA,NA,NA,0,1,1,2,0),
month6 = c(NA,NA,0,0,0,NA,NA,0,0,0,0),
month7 = c(0,0,0,0,0,0,NA,0,0,0,0),
goods1 = c(1,2,1,2,0,0,1,2,2,1,0),
goods2 = c(0,0,1,2,1,1,2,2,1,0,0),
goods3 = c(0,1,2,1,1,NA,2,1,2,1,NA),
goods4 = c(0,1,2,1,1,1,2,2,NA,NA,NA),
goods5 = c(0,1,0,1,1,1,2,2,1,NA,NA),
goods6 = c(0,1,2,1,1,1,2,2,0,0,0),
goods7 = c(NA,1,1,1,1,1,2,2,2,NA,NA))
Created on 2021-12-03 by the reprex package (v2.0.1)
I am trying to change it into a long format. I did a bit of research and pivot_longer seemed to be the best option. I have the subjectid and location as fixed variable and month1:month7 and goods1:goods6 as the time varying variable. This is how I want my final data (artificially created a part of it) to look like with every subject having a row for each of the 7 month - subject/month. Since all the column set have the same range column1-column7, I am guessing just having one column as "month" as a time indicator would be enough.
This is how I tried :
dfsales %>%
pivot_longer(
cols = starts_with("month","goods"),
names_to = "month","kind_of_goods",
names_prefix = "month","goods",
names_transform = list(month,kind_of_goods = as.integer),
values_to = "month_code","goods_code",
values_drop_na = TRUE,
)
Could anyone help me point out and explain my mistake or show if there is an easier/better way to do this? Thank you