Why does spreading this tibble fail? How could you add a new
column to fix the problem?
people <- tribble(
~name, ~key, ~value,
#-----------------|--------|------
"Phillip Woods", "age", 45,
"Phillip Woods", "height", 186,
"Phillip Woods", "age", 50,
"Jessica Cordero", "age", 37,
"Jessica Cordero", "height", 156
)
pivot_wider
is now preferred to spread
. There were names with differing ages, so the snippet below distinguishes them.
suppressPackageStartupMessages({
library(tidyr)
library(dplyr)
})
people <- tibble::tribble(
~name, ~key, ~value,
#-----------------|--------|------
"Phillip Woods, Jr.", "age", 45,
"Phillip Woods, Jr.", "height", 186,
"Phillip Woods, Sr.", "age", 75,
"Jessica Cordero", "age", 37,
"Jessica Cordero", "height", 156
)
people %>%
group_by(name) %>%
pivot_wider(names_from = key, values_from = value)
#> # A tibble: 3 × 3
#> # Groups: name [3]
#> name age height
#> <chr> <dbl> <dbl>
#> 1 Phillip Woods, Jr. 45 186
#> 2 Phillip Woods, Sr. 75 NA
#> 3 Jessica Cordero 37 156
system
Closed
3
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.