How to write a function where input is row of the dataframe and output is another dataframe?

Viewed 41

I have a table that has 3 columns, name, start and end. I'm trying to write (preferably using tidyverse) function that will take each row of that table and create (later bind all outputs) dataframe based on the logic. Obviously I need seq, but I can't figure out what function use to process the input. I tried with map_df and rowwise but no luck. Any ideas? Thanks in advance!

Here is example

input

name|start|end
A   | 1   | 3
B   | 1   | 4

expected output

Name|value
A   |1
A   |2
A   |3
B   |1
B   |2
B   |3
B   |4

1 Answers

We can use map2

library(dplyr)
library(purrr)
library(tidyr)
df1 %>%
      transmute(name, value = map2(start, end, `:`)) %>%
      unnest(c(value))
# A tibble: 7 x 2
#  name  value
#  <fct> <int>
#1 A         1
#2 A         2
#3 A         3
#4 B         1
#5 B         2
#6 B         3
#7 B         4

Or with rowwise

df1 %>%
   rowwise %>%
   transmute(name, value = list(start:end)) %>%
   unnest(c(value))

Or in base R with stack and Map

stack(setNames(do.call(Map, c(f = `:`, df1[-1])), df1$name))

data

df1 <- data.frame(name = c('A', 'B'), start = c(1, 1), end = c(3, 4))
Related