简体   繁体   中英

map along a vector and output a data.frame column of nested lists (or nested data.frames) using purrr family of functions?

I'm trying to map across a vector, and the output of each element of the input vector is itself a vector. In other words, the output of the first element of the vector, is a vector. And the same for the output of the second, third, fourth etc.

Minimal reproducible example

library(purrr)
library(tidyverse)

set.seed(123)
input <- c(1, 2, 3)
rand <- runif(3)


data.frame(input=input) %>% 
  map_df(function(x) { x * rand}) 

#   input
#   <dbl>
# 1 0.288
# 2 1.58 
# 3 1.23 

The actual returns only a single value per row, whereas the desired output is a nested vector, list, or, data.frame (something sensible with 3 elements per row instead of 1).

How can this be done?

One option is to use map within mutate to create a list within the dataframe.

data.frame(input=input) %>% 
 mutate(rand_3 = map(input, function(x) x * rand))


#------
  input                          rand_3
1     1 0.2875775, 0.7883051, 0.4089769
2     2 0.5751550, 1.5766103, 0.8179538
3     3 0.8627326, 2.3649154, 1.2269308

You can use rowwise :

library(dplyr)

df <- data.frame(input) 

df %>%
  rowwise() %>%
  mutate(rand_3 = list(input * rand))

#  input              rand_3
#1     1 0.288, 0.788, 0.409
#2     2 0.575, 1.577, 0.818
#3     3 0.863, 2.365, 1.227

Or lapply in base R:

df$rand_3 <- lapply(df$input, `*`, rand)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM