How can I rename a column within a grouped dplyr tibble, depending on a certain row value? The following graphic shows how my tibble looks before and how it should be looking after the manipulation.
I have tried the following code, but did not manage to write a column rename function that is able to state the new column name flexibly from the "name" column.
library(dplyr)
df <- data.frame(
"splitvar"=c(1,1,1,2,2,3,3,3,3),
"value"=c(1,4,2,5,6,9,11,13,12),
"name"=c("Harold","Harold","Harold","Jane","Jane","George","George","George","George"),
stringsAsFactors=F
)
grouped_tbl <- df %>%
group_by( splitvar ) %>%
eval(parse(
paste0("rename(",unique(name)," = value)")
))
Related: Replacement for "rename" in dplyr
Like this:
library(tidyverse)
df %>%
split(.$splitvar) %>%
map(~rename(., !!unique(.$name) := "value"))
It took some time getting my head around the quosure-thing, but try and take a look at programming with dplyr
The output of the code is:
$`1`
splitvar Harold name
1 1 1 Harold
2 1 4 Harold
3 1 2 Harold
$`2`
splitvar Jane name
4 2 5 Jane
5 2 6 Jane
$`3`
splitvar George name
6 3 9 George
7 3 11 George
8 3 13 George
9 3 12 George