Reputation: 1986
I want to apply a function inside a tibble but I don't want to explicitly Name the columns. E.G.
library(tidyverse)
library(tidyselect)
test = tibble(var1 = c("la", "le", "lu"), var2 = c("ma", "me", "mu"), var3 = c("fi", "fa", "fu"), dummy=1)
with_funct = test %>% mutate(blub = pmap_chr(list(var1, var2, var3), paste, sep='+'))
I get the expected result:
# A tibble: 3 x 5
var1 var2 var3 dummy blub
<chr> <chr> <chr> <dbl> <chr>
1 la ma fi 1 la+ma+fi
2 le me fa 1 le+me+fa
3 lu mu fu 1 lu+mu+fu
But instead of writing list(var1, var2, var3)
I'd prefer to use starts_with("var")
but this does not work out.
So if I use
with_funct = test %>% mutate(blub = pmap_chr(starts_with("var"), paste, sep='+'))
I get an
"Error: No tidyselect variables were registered"
I'd appreciate any help.
Upvotes: 2
Views: 401
Reputation: 36086
You could use select()
inside pmap_chr()
to work on just the columns that starts with "var". I use the dot to refer to the dataset being used in mutate()
.
One reasons this works is because pmap()
works rowwise across a tibble. The way I'm using this the columns are used in the function (paste()
in your case) in the order they appear in the dataset.
test %>%
mutate(blub = pmap_chr(select(., starts_with("var")), paste, sep='+'))
# A tibble: 3 x 5
var1 var2 var3 dummy blub
<chr> <chr> <chr> <dbl> <chr>
1 la ma fi 1 la+ma+fi
2 le me fa 1 le+me+fa
3 lu mu fu 1 lu+mu+fu
Upvotes: 2
Reputation: 481
Try this:
with_funct2 = test %>% mutate(blub = pmap_chr(test %>% select(starts_with("var")), paste, sep='+'))
Hope it helps
Upvotes: 1