2

I am working with a dataset that contains many columns that are similarly named (ex thing_1 , thing_2, blargh_1, blargh_2, fizz_1, fizz_2), and I've been trying to write a function that takes in a string (such as fizz) and performs some operation on all superstrings of the column (such as fizz_1 + fizz_2).

So far, I have structured my code into something that looks something like:

newData <- data %>%
    mutate(fizz = f("fizz"))

f <- function(name) {
name_1 + name_2
}

where f as written obviously doesn't work. I've toyed around with assign, but not been terribly successful. I'm also open to other ways to tackle the problem (maybe a function that takes in a dataset and the string). Thanks!

1 Answer 1

4

If we are creating a function then make use of the select_helpers which can take starts_with or ends_with or match as arguments

library(dplyr)
library(purrr)
f1 <- function(data, name){
          data %>%
              mutate(!! name := select(., starts_with(name)) %>% reduce(`+`))
    }

f1(df1, "fizz")
f1(df1, "blargh")
f1(df1, "thing")
#   thing_1 thing_2 thing_3 fizz_1 fizz_2 blargh_1 blargh_2 thing
#1       1       6      11      2      3        4        5    18
#2       2       7      12      3      4        5        6    21
#3       3       8      13      4      5        6        7    24
#4       4       9      14      5      6        7        8    27
#5       5      10      15      6      7        8        9    30

Or specify select(., matches(str_c("^", name, "_\\d+$")))

data

df1 <- data.frame(thing_1 = 1:5, thing_2 = 6:10, thing_3 = 11:15, 
    fizz_1 = 2:6, fizz_2 = 3:7, blargh_1 = 4:8, blargh_2 = 5:9)

          
Sign up to request clarification or add additional context in comments.

4 Comments

Interesting! Is is possible to explain !! name := ? thanks
Thanks! That's a very neat and compact solution
@ZhiqiangWang That notation is specific to tidyverse for assignment (:=) with lhs being a object. here, we evaluate (!!) to get the value in name instead of creating name as the column name
Thanks a lot. This is handy and I will definitely try it with my work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.