Convert column dummies into row dummies in R

70 views Asked by At

I'm trying to convert several column dummies into one dummies.

What I have now:

HS2002 <- c(30343, 30344, 30345, 30346, 30349)
Original.rate <- c(10, 12, 10, 13, 2)
2004 <- c(0, 0, 0, 1, 0)
2005 <- c(0, 1, 0, 1, 0)
2006 <- c(1, 1, 0, 1, 0)
format1 <- data.frame(HS2002, Original.rate, `2004`, `2005`, `2006`)

What I want to have:

HS2002 <- c(30343, 30343, 30343, 30344, 30344, 30344, 30345, 30345, 30345, 30346, 30346 30346, 30349, 30349,30349)
Year <- c(2004, 2005, 2006,2004, 2005, 2006,2004, 2005, 2006,2004, 2005, 2006,2004, 2005, 2006,)
Original.rate(10, 10, 10, 12, 12, 12, 10, 10, 10, 13, 13, 13, 2, 2, 2)
Treatment <- (0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0)
format2 <- data.frame(HS2002, Year, Original.rate, Treatment)

The dataset I'm actually using has 2004 to 2016 data, and thousands of different HS2002 codes. I suspect the solution is some variation expand.grid or what's illustrated in How to convert multiple columns to individual rows in R, but I haven't gotten melt in reshape2 to work yet.

Fairly new to R at this point, so I'm hoping I don't have to resort to for loop yet. Any ideas? Thanks in advance.

0

There are 0 answers