I'm trying to assemble a list of files in a data frame column, but trying to keep only the unique values is causing me fits. I tried using lists, and then tried using character strings, and have failed at both. The group_by's are part of the process. (the actual application involves census blocks, census block groups, and sea-level rise raster files)
library(tidyverse)
library(stringr)
foo1 <- tribble(~Grpby, ~Listvar,
"aa", "M",
"aa", "N",
"ba", "M",
"ca", "N,O",
"ca", "N",
"cb", "M"
)
foo2 <- foo1 %>%
group_by(Grpby) %>%
reframe(Listvar=paste(Listvar, collapse=","),
Grpby2=str_sub(Grpby, 2,2))
foo3 <- foo2 %>%
group_by(Grpby2) %>%
summarise(Listvar=first(paste(Listvar, collapse=",")))
foo3
foo4 <- foo3 %>%
mutate(Newvar=unique(unlist(str_split(Listvar, pattern=","))))
foo3:
Grpby2 Listvar
<chr> <chr>
a M,N,M,N,M,N,O,N,N,O,N
b M
Then:
Error in `mutate()`:
ℹ In argument: `Newvar = unique(unlist(str_split(Listvar, pattern = ",")))`.
Caused by error:
! `Newvar` must be size 2 or 1, not 3.
Backtrace:
1. foo3 %>% ...
9. dplyr:::dplyr_internal_error(...)