o4-mini-2025-04-16· OpenAI
LMArena Human Preference 140K
Hi, I have a dataframe with the columns ha312, ha313, ha314, etc. and would like to turn…
- User
Hi, I have a dataframe with the columns ha3_1_2, ha3_1_3, ha3_1_4, etc. and would like to turn the first underscore into a dot for all columns that start with ha3. I would like to use dplyr
- Assistant
Here’s a quick dplyr-only solution—using
rename_with()+stringr::str_replace()—that will look for all columns starting with “ha3” and replace only the first “_” with a “.”:library(dplyr) library(stringr) df %>% rename_with( ~ str_replace(., "^(ha3)_", "\\1."), # pattern: “ha3_” → “ha3.” starts_with("ha3") )Explanation:
starts_with("ha3")picks out all columns whose names begin with “ha3”.str_replace(., "^(ha3)_", "\\1.")finds the first underscore immediately after “ha3” and swaps it for a dot.^(ha3)_→ match “ha3_” at the start of the string\\1.→ keep “ha3” (that’s capture group 1) and add a “.”
Example
df <- tibble( ha3_1_2 = 10, ha3_1_3 = 20, ha3_extra = 30, other_col = 40 ) df %>% rename_with(~ str_replace(., "^(ha3)_", "\\1."), starts_with("ha3")) #> # A tibble: 1 × 4 #> ha3.1_2 ha3.1_3 ha3.extra other_col #> <dbl> <dbl> <dbl> <dbl> #> 1 10 20 30 40If you’d rather not pull in stringr, you can use base-R’s
sub():df %>% rename_with(~ sub("^(ha3)_", "ha3.", .x), starts_with("ha3"))Both will yield the same column names (
ha3.1_2,ha3.1_3,ha3.extra, …). 🎉
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.