Home > Software engineering >  Change values of dataframe into column names and assign value to them
Change values of dataframe into column names and assign value to them

Time:05-18

I've got a small problem. I want "2019" and "2020" as my column names and as their values the matching values of "counter" and delete the duplicate names. It looks like this:

# A tibble: 6 x 3
# Groups:   Full.Name [3]
  Full.Name             year counter
  <chr>                <dbl>   <int>
1 A. Patrick Beharelle  2019    5541
2 A. Patrick Beharelle  2020    3269
3 Aaron P. Graft        2019     165
4 Aaron P. Graft        2020     200
5 Aaron P. Jagdfeld     2019       4
6 Aaron P. Jagdfeld     2020       5

And I want it to look like this:

# A tibble: 6 x 3
# Groups:   Full.Name [3]
  Full.Name             2019    2020
  <chr>                <int>   <int>
1 A. Patrick Beharelle  5541    3269
2 Aaron P. Graft         165     200
3 Aaron P. Jagdfeld        4       5

I know that numbers as a col name isn't a smart thing to do, so it is only to demonstrate what I want to archive. I don't know what the correct term for this transition is, so I have no clue on what to look for. Maybe someone can help me archive this transformation. Thanks in advance!

CodePudding user response:

This is a classic reshaping wider - it can be done in many ways, one of which is pivot_wider() from tidyr:

library(tidyr)

data |> pivot_wider(names_from = year, values_from = counter)

Output:

#> # A tibble: 3 x 3
#>   Full.Name              `2019` `2020`
#>   <chr>                   <dbl>  <dbl>
#> 1 "A. Patrick Beharelle"   5541   3269
#> 2 "Aaron P. Graft      "    165    200
#> 3 "Aaron P. Jagdfeld   "      4      5

Created on 2022-05-17 by the reprex package (v2.0.1)

More information on reshaping datasets with tidyr is here: https://tidyr.tidyverse.org/articles/pivot.html

  • Related