Adding Empty Columns in a data frame based on variable names of previous columns in R

Viewed 30

I have a dataframe that looks like the following

ID director_name vp_name lead_name funding
1 A C E 100$
2 B D G 200$

I want to add empty columns for genders based on variables that have _name in their headers to look like the following

ID director_name director_g vp_name vp_g lead_name lead_g funding
1 A C E 100$
2 B D G 200$

All the internet help has been based on conditions that are based on values in a variable, but none on headers. At the same time, I am not sure how to give them specific names. Any help would be appreciated! Thanks!

1 Answers

Here are methods with base R and dplyr:

## base
names_to_add = grep("_", names(df), value = T)
names_to_add = sub(pattern = "_.*", replacement = "_g", x = names_to_add)
df[names_to_add] = ""
df
#   ID director_name vp_name lead_name funding director_g vp_g lead_g
# 1  1             A       C         E    100$                       
# 2  2             B       D         G    200$  

## dplyr version
# make sure to re-initialize `df` before running this version

library(dplyr)
df = df %>%
  mutate(across(contains("_"), \(x) "", .names = "{.col}_g")) %>%
  rename_with(.fn = sub, pattern = "_.*", replacement = "_g", .cols = contains("_g"))
df
#   ID director_name vp_name lead_name funding director_g vp_g lead_g
# 1  1             A       C         E    100$                       
# 2  2             B       D         G    200$  

As asked, this initializes the new columns to "" values. I'd usually prefer missing values NA, which you might want to consider.


Using this data:

df = read.table(text = 'ID  director_name   vp_name     lead_name   funding
1   A   C   E   100$
2   B   D   G   200$', header = T)
Related