'paste()ing columns whose names are stored in a variable
How do I create a new column from columns whose names are contained in a character vector?
Given these two variables:
data <- tibble(numbers = 1:10, letters = letters[1:10])
columns <- c("numbers","letters")
What command would produce this output?
# A tibble: 10 x 3
numbers letters combined
<int> <chr> <chr>
1 1 a 1-a
2 2 b 2-b
3 3 c 3-c
4 4 d 4-d
5 5 e 5-e
6 6 f 6-f
7 7 g 7-g
8 8 h 8-h
9 9 i 9-i
10 10 j 10-j
My first thought was mutate(data, combined = paste(!!columns, sep = "-")) but this does not work.
Error: Problem with `mutate()` input `combined`.
x Input `combined` can't be recycled to size 10.
ℹ Input `combined` is `paste(c("numbers", "letters"))`.
ℹ Input `combined` must be size 10 or 1, not 2.
Solution 1:[1]
not the prettiest but this should work
do.call(
paste,
c(data[, columns], list(sep = '-'))
)
Solution 2:[2]
cbind( data , combined = paste( data[[ columns[1] ]], data[[ columns[2] ]], sep=“-“)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | MichaelChirico |
| Solution 2 | IRTFM |
