Darius
Darius

Reputation: 489

Combining "mutate" and "across" from dplyr and functions from stringr

PROBLEM STATEMENT

I have a table in which some columns begin with a string that I would like to remove. I have tried to do that by using the new "across" functionality from dplyr, and the functions from stringr to manipulate strings, but I have failed (that's why I am here!).

EXAMPLE CODE

library(tidyverse)

# Generate a short mock-up table
set.seed(1)
mockup <- tibble(n_col1 = sample(1:10, 5, FALSE),
                 v_col2 = sample(letters, 5, FALSE),
                 col3 = sample(10:20, 5, TRUE),
                 col4 = sample(LETTERS, 5, FALSE)) # More columns beginning with "n_", "v_" or nothing

# Remove the "n_" or "v_" strings from the column names
# This is as far as my skills go...
mockup <- mockup %>% mutate(across(starts_with(c("n_", "v_")), str_remove))

QUESTION

Any ideas how to do this, either in my way or in a different way, in an short and efficient fashion?

Upvotes: 2

Views: 463

Answers (2)

akrun
akrun

Reputation: 887028

We can use str_remove with dplyr

library(dplyr)
library(stringr)
mockup %>%
    rename_with(~ str_remove(., '^[nv]_'))
# A tibble: 5 x 4
#   col1 col2   col3 col4 
#  <int> <chr> <int> <chr>
#1     9 w        10 N    
#2     4 k        14 J    
#3     7 n        14 G    
#4     1 r        19 I    
#5     2 s        15 O   

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388862

across is used to manipulate values in the column and not the column names. You could use the new rename_with to rename the columns.

library(dplyr)
mockup %>%  rename_with(~sub('^(n|v)_', '', .))
#rename_all in old dplyr
#mockup %>%  rename_all(~sub('^(n|v)_', '', .))

#   col1 col2   col3 col4 
#  <int> <chr> <int> <chr>
#1     9 w        10 N    
#2     4 k        14 J    
#3     7 n        14 G    
#4     1 r        19 I    
#5     2 s        15 O    

Or doing this in base R :

names(mockup) <- sub('^(n|v)_', '', names(mockup))

Upvotes: 3

Related Questions