Home > Mobile >  Append output from iterative mapped function
Append output from iterative mapped function

Time:09-16

This is a follow-up to a previous question: Read functions as text and use for plotting

The output of the mapped function...

data %>% 
  bind_cols(
    map(.x = models,.f = text_model) %>% 
      set_names(models) %>% 
      bind_rows(.id = "model") 
  )

...generates a data frame with the results of each function written to a separate column (with the function included in the column headers).

However, it would be best to have the output from each function appended such that all results are included in the same column with a separate column to keep track of which function ("model001", "model002",..."model500") generated the results.

How can the code from the previous question (Read functions as text and use for plotting) be adjusted to write the results in this manner?

Edit: Someone suggested Read functions as text and use for plotting as an answer, but this post is a follow-up to that one asking about how the output can be written to a single column (rather than a sperate column for each function).

CodePudding user response:

Given the other answer, we can pivot the data

data %>% 
  bind_cols(
    map(.x = models,.f = text_model) %>% 
      set_names(models_names) %>% 
      bind_rows(.id = "model") 
  ) %>% 
  pivot_longer(cols = model1:model2,names_to = "model")

# A tibble: 200 x 6
       A       B      C       D model  value
   <dbl>   <dbl>  <dbl>   <dbl> <chr>  <dbl>
 1 0.833  0.538   0.647  1.65   model1  22.9
 2 0.833  0.538   0.647  1.65   model2  57.9
 3 2.07   1.20   -0.748 -2.04   model1  35.3
 4 2.07   1.20   -0.748 -2.04   model2  70.3
 5 0.880 -0.199   1.08   1.04   model1  29.2
 6 0.880 -0.199   1.08   1.04   model2  64.2
 7 0.252  0.400   1.45  -0.0645 model1  15.6
 8 0.252  0.400   1.45  -0.0645 model2  50.6
 9 0.746  0.0943 -1.00   1.44   model1  20.4
10 0.746  0.0943 -1.00   1.44   model2  55.4
# ... with 190 more rows
  • Related