I have a dataframe where I would like to separate each column into two columns. Each column follow the same pattern "x_y"
test <- structure(list(A = c("511686_0.112", "503316_0.105", "476729_0.148",
"229348_0.181", "385774_0.178", "209277_0.029", "299921_0.124",
"486771_0.123", "524146_0.07", "496030_0.119"), B = c("363323_0.103",
"260709_0.105", "361361_0.148", "731426_0.181", "222799_0.178",
"140296_0.029", "388191_0.124", "500136_0.123", "487344_0.07",
"267303_0.119"), C = c("362981_0.103", "260261_0.105", "360912_0.148",
"730423_0.181", "222351_0.178", "139847_0.029", "379717_0.124",
"499662_0.123", "486869_0.07", "266907_0.119")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -10L))
Using the separate functions seems to work well for one column. How can I apply this same function to each of the columns?
# works
test2 <- test %>%
separate_wider_delim(A, delim = "_", names_sep = "_")
> test2
# A tibble: 10 × 4
A_1 A_2 B C
<chr> <chr> <chr> <chr>
1 511686 0.112 363323_0.103 362981_0.103
2 503316 0.105 260709_0.105 260261_0.105
3 476729 0.148 361361_0.148 360912_0.148
4 229348 0.181 731426_0.181 730423_0.181
5 385774 0.178 222799_0.178 222351_0.178
6 209277 0.029 140296_0.029 139847_0.029
7 299921 0.124 388191_0.124 379717_0.124
8 486771 0.123 500136_0.123 499662_0.123
9 524146 0.07 487344_0.07 486869_0.07
10 496030 0.119 267303_0.119 266907_0.119
# doesn't work
test3 <- test %>%
mutate(across(everything(), separate_wider_delim, delim = "_", names_sep = "_"))
Error in `mutate()`:
ℹ In argument: `across(everything(), separate_wider_delim, delim = "_", names_sep = "_")`.
Caused by error in `across()`:
! Can't compute column `A`.
Caused by error in `fn()`:
! `data` must be a data frame, not a character vector.
Run `rlang::last_error()` to see where the error occurred.
For specific columns why not simply:
test2 <- test %>%
separate_wider_delim(cols = A:C,delim = '_', names_sep = '_')
test2
Or to expand to all columns in a dataframe:
test2 <- test %>%
separate_wider_delim(cols = everything(),delim = '_', names_sep = '_')
test2