Transforming a nested data frame with varying number of elements

一笑奈何 提交于 2019-12-05 15:46:13

This will avoid by-row operations, which will be important if you have a lot of rows.

library(data.table)

rbindlist(df$l, fill = T, id = 'row')[, v := df$v[row]][]
#   row n1 n2  v
#1:   1  a  1 p1
#2:   1  b  2 p1
#3:   2  d NA p2
#4:   3  e  3 p3

Using purrr::pmap_df, within each row of df, we combine v and l into a single data frame and then combine all of the data frames into a single data frame.

library(tidyverse)

pmap_df(df, function(v,l) {
  data.frame(v,l)
})
   v n1   n2
1 p1  a    1
2 p1  b    2
3 p2  d <NA>
4 p3  e    3

A solution using dplyr and tidyr. suppressWarnings is not required. Because when you created data frames, there are factor columns, suppressWarnings is to suppress the warning message when combining factors.

library(dplyr)
library(tidyr)

df1 <- suppressWarnings(df %>%
  mutate(v = unlist(.$v)) %>%
  unnest())
df1
#    v n1   n2
# 1 p1  a    1
# 2 p1  b    2
# 3 p2  d <NA>
# 4 p3  e    3
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!