I have a df that looks like below and I would like to modify it to something that looks like the one on the right. How should I do that?
I tried to use map
but in the wrong way for sure. Could anyone guide me on this?
df <- structure(list(`Student Enrollment` = 750, `Faculty Number` = 21,
Graduated = 65), row.names = c(NA, -1L), class = c("tbl_df", "tbl", "data.frame"))
df %>%
map(.,~paste0(colnames(.), "(N=", ., ")"))
CodePudding user response:
Another possible solution:
library(tidyverse)
pmap_dfr(df, ~ str_c(names(df), " (", c(...), ")") %>% set_names(names(df)))
#> # A tibble: 1 × 3
#> `Student Enrollment` `Faculty Number` Graduated
#> <chr> <chr> <chr>
#> 1 Student Enrollment (750) Faculty Number (21) Graduated (65)
CodePudding user response:
You should use across
with mutate
to modify multiple columns at once; to refer to the current column, use cur_column
:
df %>%
mutate(across(everything(), ~ paste0(cur_column(), " (N=", .x, ")")))
or with purrr::imap_dfr
:
df %>%
imap_dfr(~ paste0(.y, " (N=", .x, ")"))
output
`Student Enrollment` `Faculty Number` Graduated
1 Student Enrollment (N=750) Faculty Number (N=21) Graduated (N=65)
CodePudding user response:
Base R solution:
df[] <- lapply(
seq_len(ncol(df)),
function(i){
paste0(
names(df)[i],
" (N=",
df[, i,drop = TRUE],
")"
)
}
)