First we melt
, to get all the plz
values into one column (moving from "wide" to "long" format). Then we just remove the "variable" column because we don't need to differentiate between plz
and plz1
, and we rename value
to plz
.
require(reshape2)
df1 <- data.frame(name=c("city","village"),code=c(10322,10321),plz=c(7041,7043),plz1=c(7044,7044),plz2=c(7043,NA))
df1 <- melt(df1, id.vars=c("name", "code"))
df1 <- df1[,-3]
names(df1) <- c("name", "code", "plz")
name code plz
1 city 10322 7041
2 village 10321 7043
3 city 10322 7044
4 village 10321 7044
5 city 10322 7043
6 village 10321 NA
We can simplify a little further incorporating the dplyr
package:
require(dplyr)
require(reshape2)
df1 %>% melt(id.vars=c("name", "code")) %>%
select(-variable) %>%
rename(plz=value)