I have a nested dataframe tb
which looks like that:
>tb
# A tibble: 26 x 3
league fdj_data five38_data
<chr> <list> <list>
1 Ch.D1 Danemark <tibble [14 x 1]> <tibble [14 x 1]>
2 Ch.D1 Ecosse <tibble [10 x 1]> <tibble [14 x 1]>
3 Ligue 2 <tibble [20 x 1]> <tibble [19 x 1]>
4 Serie B <tibble [18 x 1]> <tibble [21 x 1]>
5 Liga Segunda <tibble [20 x 1]> <tibble [20 x 1]>
6 Ch.D1 Pays-Bas <tibble [18 x 1]> <tibble [21 x 1]>
7 Ch.D1 Grèce <tibble [12 x 1]> <tibble [16 x 1]>
8 Ch.D1 Suède <tibble [16 x 1]> <tibble [19 x 1]>
9 Ch.D1 Turquie <tibble [18 x 1]> <tibble [21 x 1]>
10 Ch.D1 Russie <tibble [14 x 1]> <tibble [19 x 1]>
# ... with 16 more rows
I also have a function (let's call it func
) which takes 2 character vectors (possibly of different lengths) and output another character vector (same length length as the first arg)
I want to add another column which contains, for each row, func(fdj_data, five38_data)
I've tried
tb %>%
mutate(new_var = func(fdj_data, five38_data))
and
tb %>%
mutate(fdj_data = as.character(fdj_data),
five38_data = as.character(five38_data)) %>%
mutate(new_var = func(fdj_data, five38_data))
But both don't work. I also tried with purrr::map()
but I wasn't more successful
Have you got any idea ?
You should not have to experience any problem if your func
is properly vectorized. Please see example below:
library(tibble)
library(dplyr)
set.seed(123)
func <- function(fdj_data, five38_data) {
sample(LETTERS, length(fdj_data), replace = TRUE)
}
tb <- tibble(league = paste0(sample(letters, 26, replace = TRUE), 1:26))
tb$fdj_data <- lapply(sample(10:22, 26, replace = TRUE), function(x)tibble(rnorm(x)))
tb$five38_data <- lapply(sample(10:22, 26, replace = TRUE), function(x)tibble(rnorm(x)))
tb
tb %>%
mutate(new_var = func(fdj_data, five38_data))
Output:
# A tibble: 26 x 4
league fdj_data five38_data new_var
<chr> <list> <list> <chr>
1 h1 <tibble [17 x 1]> <tibble [14 x 1]> C
2 u2 <tibble [17 x 1]> <tibble [19 x 1]> U
3 k3 <tibble [13 x 1]> <tibble [10 x 1]> F
4 w4 <tibble [11 x 1]> <tibble [20 x 1]> R
5 y5 <tibble [22 x 1]> <tibble [16 x 1]> L
6 b6 <tibble [21 x 1]> <tibble [19 x 1]> F
7 n7 <tibble [18 x 1]> <tibble [18 x 1]> Z
8 x8 <tibble [20 x 1]> <tibble [17 x 1]> L
9 o9 <tibble [10 x 1]> <tibble [19 x 1]> A
10 l10 <tibble [16 x 1]> <tibble [18 x 1]> Y
# ... with 16 more rows
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.