Reputation: 97
I've got a dataframe that contains information about municipalities and estates like below:
df>
Municipality State
Campos RJ
Angra RJ
Campinas SP
Vitoria ES
and I want to combine both columns and create another one like:
Municipality State Municipality_State
Campos RJ Campos (RJ)
Angra RJ Angra (RJ)
Campinas SP Campinas (SP)
Vitoria ES Vitoria (ES)
I appreciate any comment
Regards,
Upvotes: 1
Views: 43
Reputation: 420
This should work for you:
df$Municipality_State <- paste0(df$Municipality, " (", df$State, ")")
RESULTS:
Municipality <- c('Campos','Angra','Campinas','Vitoria')
State <- c('RJ','RJ','SP','ES')
df <- data.frame(Municipality, State)
df$Municipality_State <- paste0(df$Municipality, " (", df$State, ")")
df
Municipality State Municipality_State
1 Campos RJ Campos (RJ)
2 Angra RJ Angra (RJ)
3 Campinas SP Campinas (SP)
4 Vitoria ES Vitoria (ES)
Upvotes: 1
Reputation: 2678
You can use paste0
from base R to achieve this:
df$Muncipality_State <- paste0(df$Municipality, " (", df$State, ")")
df
# Municipality State Muncipality_State
#1 Campos RJ Campos (RJ)
#2 Angra RJ Angra (RJ)
#3 Campinas SP Campinas (SP)
#4 Vitoria ES Vitoria (ES)
df <- structure(list(Municipality = structure(c(3L, 1L, 2L, 4L), .Label = c("Angra", "Campinas", "Campos", "Vitoria"), class = "factor"), State = structure(c(2L, 2L, 3L, 1L), .Label = c("ES", "RJ", "SP"), class = "factor")), class = "data.frame", row.names = c(NA, -4L))
Upvotes: 3
Reputation: 2717
Try this one
df <- read_table("Municipality State
Campos RJ
Angra RJ
Campinas SP
Vitoria ES")
df %>%
mutate(Municipality_State = glue::glue("{Municipality} ({State})"))
# A tibble: 4 x 3
Municipality State Municipality_State
<chr> <chr> <glue>
1 Campos RJ Campos (RJ)
2 Angra RJ Angra (RJ)
3 Campinas SP Campinas (SP)
4 Vitoria ES Vitoria (ES)
Upvotes: 2