How could I collect this table into the list below?
df<-tibble(name = c("ageThenCode", "ageThenCode", "ageThenCode", "ageThenCode", "ageThenCode", "ageThenCode", "eduCode", "eduCode", "eduCode", "regioCat", "regioCat", "regioCat", "teltipCode", "teltipCode", "teltipCode"), value = factor(c("1", "2", "3", "4", "5", "6", "1", "2", "3", "1", "2", "3", "1", "2", "3")), freq = c(0.042, 0.222, 0.208, 0.222, 0.149, 0.157, 0.155, 0.591, 0.254, 0.373, 0.34, 0.287, 0.271, 0.524, 0.205))
list(
ageThenCode=c("1"=0.042, "2"=0.222, "3"=0.208, "4"=0.222, "5"=0.149, "6"=0.157),
eduCode=c("1"=.37, "2"=.38, "3"=.25),
regionCode=c("1"=.373, "2"=.34, "3"=.287),
teltipCode=c("1"=.271, "2"=.524,"3"=.205)
)
I was trying something like this, but couldn't quite make it:
df %>%
group_by(name) %>%
summarise(cat = list(value=freq) ) %>%
pivot_wider(names_from = name, values_from = cat)
CodePudding user response:
Create a named vector and split
would be the easiest and fast way in base R
with(df, split(setNames(freq, value), name))
Or to create the same in tidyverse
library(dplyr)
library(purrr)
library(tibble)
df %>%
split(.$name) %>%
map(~ deframe(.x[-1]))
-output
$ageThenCode
1 2 3 4 5 6
0.042 0.222 0.208 0.222 0.149 0.157
$eduCode
1 2 3
0.155 0.591 0.254
$regioCat
1 2 3
0.373 0.340 0.287
$teltipCode
1 2 3
0.271 0.524 0.205