I wrote a function using map2
that aims to produce a dataframe or a list of dataframes. My problem is that this function produces individual tables that are not assigned to an object. My desired output is a dataframe which stores the output tibble for each iteration of the vectorised loop.
df_coefs <- list()
df <-
tibble(names = c("john", "charlie", "lucy"), colours = c("green", "grey", "silver"))
funx <- function(name, colour) {
coef <- runif(1, 0, 30)
df_coefs[[i]] <-
tibble_row(names = name,
colours = colour,
coefs = coef)
}
map2(.x = df$names,
.y = df$colours,
.f = funx)
[[1]]
# A tibble: 1 × 3
names colours coefs
<chr> <chr> <dbl>
1 john green 11.1
[[2]]
# A tibble: 1 × 3
names colours coefs
<chr> <chr> <dbl>
1 charlie grey 3.73
[[3]]
# A tibble: 1 × 3
names colours coefs
<chr> <chr> <dbl>
1 lucy silver 29.4
names colours coefs
<chr> <chr> <dbl>
1 john green 11.1
2 charlie grey 3.73
3 lucy silver 29.4
The assignment with [i]
seems to be a typo
funx <- function(name, colour) {
coef <- runif(1, 0, 30)
tibble_row(names = name,
colours = colour,
coefs = coef)
}
Other than that, if we need to collapse the rows, use the suffix _dfr
in map
library(purrr)
map2_dfr(.x = df$names,
.y = df$colours,
.f = funx)
# A tibble: 3 × 3
names colours coefs
<chr> <chr> <dbl>
1 john green 14.3
2 charlie grey 25.8
3 lucy silver 13.1