-1

My data looks like:

data.frame(name=c("city","village"),code=c(10322,10321),plz=c(7041,7043),plz1=c(7044,7044),plz2=c(7043,NA))

What's the smartest way to convert column plz1 and column plz2 to plz:

name  code   plz

city  10322  7041

city  10322  7044

city  10322  7043
rupi42
  • 69
  • 7

2 Answers2

0

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)
Mako212
  • 6,787
  • 1
  • 18
  • 37
0

Use tidyr and dplyr packages.

df <- data.frame(name=c("city","village"),code=c(10322,10321), plz=c(7041,7043),plz1=c(7044,7044),plz2=c(7043,NA))
df %>% tidyr::gather(type, plz, plz:plz2) %>% dplyr::select(-type) %>% dplyr::filter(name == 'city')

#name   code    plz
#city   10322   7041
#city   10322   7044
#city   10322   7043