简体   繁体   中英

How to combine columns based on contingencies?

I have the following df:

SUMLEV STATE COUNTY AGEGRP TOT_POP TOT_MALE
50     1      1    0   55601    26995
50     7      33   0  218022   105657
50     14     500  0   24881    13133
50     4      70   0   22400    11921
50     3      900  0   57840    28500
50     22     11   0   10138     5527

I would like to make a new columns named CODE based on the columns state and county . I would like to paste the number from state to the number from county . However, if county is a single or double digit number, I would like it to have zeroes before it, like 001 and 033 .

Ideally the final df would look like:

SUMLEV STATE COUNTY AGEGRP TOT_POP TOT_MALE CODE
50     1      1    0   55601    26995     1001
50     7      33   0  218022   105657     7033
50     14     500  0   24881    13133     14500
50     4      70   0   22400    11921     4070
50     3      900  0   57840    28500     3900
50     22     11   0   10138     5527     22011

Is there a short, elegant way of doing this?

We can use sprintf

library(dplyr)
df %>%
    mutate(CODE = sprintf('%d%03d', STATE, COUNTY))
# SUMLEV STATE COUNTY AGEGRP TOT_POP TOT_MALE  CODE
#1     50     1      1      0   55601    26995  1001
#2     50     7     33      0  218022   105657  7033
#3     50    14    500      0   24881    13133 14500
#4     50     4     70      0   22400    11921  4070
#5     50     3    900      0   57840    28500  3900
#6     50    22     11      0   10138     5527 22011

If we need to split the column 'CODE' into two, we can use separate

library(tidyr)
df %>%
    mutate(CODE = sprintf('%d%03d', STATE, COUNTY)) %>% 
    separate(CODE, into = c("CODE1", "CODE2"), sep= "(?=...$)")

Or extract to capture substrings as a group

df %>%
    mutate(CODE = sprintf('%d%03d', STATE, COUNTY)) %>% 
    extract(CODE, into = c("CODE1", "CODE2"), "^(.*)(...)$")

Or with str_pad

library(stringr)
df %>%
    mutate(CODE = str_c(STATE, str_pad(COUNTY, width = 3, pad = '0')))

Or in base R

df$CODE <- sprintf('%d%03d', df$STATE, df$COUNTY)

data

df <- structure(list(SUMLEV = c(50L, 50L, 50L, 50L, 50L, 50L), STATE = c(1L, 
7L, 14L, 4L, 3L, 22L), COUNTY = c(1L, 33L, 500L, 70L, 900L, 11L
), AGEGRP = c(0L, 0L, 0L, 0L, 0L, 0L), TOT_POP = c(55601L, 218022L, 
24881L, 22400L, 57840L, 10138L), TOT_MALE = c(26995L, 105657L, 
13133L, 11921L, 28500L, 5527L)), class = "data.frame", row.names = c(NA, 
-6L))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM