Home > other >  appending tibbles using purrr::map
appending tibbles using purrr::map

Time:11-04

Background

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.

Reprex

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)

Current output

[[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

Desired output

  names colours coefs
  <chr> <chr>   <dbl>
1 john  green    11.1
2 charlie grey   3.73
3 lucy  silver   29.4

CodePudding user response:

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

CodePudding user response:

Why not just:

df <- tibble(
    names = c("john", "charlie", "lucy"), 
    colours = c("green", "grey", "silver"),
    coef = runif(3, 0, 30)
)
df
# A tibble: 3 x 3
  names   colours  coef
  <chr>   <chr>   <dbl>
1 john    green    4.37
2 charlie grey    17.8 
3 lucy    silver  19.1 
  • Related