在数据帧 R 中取消嵌套数据帧 [英] unnest dataframe within dataframe R

查看:42
本文介绍了在数据帧 R 中取消嵌套数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想取消嵌套此数据框.

I would like to unnest this dataframe.

df <- tibble(
  bears = c(1,2,3),
  eagles = tibble(
    talons = c(2,3,4),
    beaks = c("x","y","z")
  )
)

看起来像

tibble(
  bears = c(1,2,3),
  talons = c(2,3,4),
   beaks = c("x","y","z")
)

我曾尝试使用 unnestunnest_widerflattenunlist 但都无济于事.例如,如果我运行,

I have tried using unnest and unnest_wider, flatten and unlist but to no avail. If I run, for example,

test <- df %>%
  unnest_wider(eagles, names_sep = "_")

错误是

Error: Assigned data `map(data[[col]], vec_to_wide, col = col, names_sep = names_sep)` must be compatible with existing data.
x Existing data has 3 rows.
x Assigned data has 2 rows.
ℹ Only vectors of size 1 are recycled.

我不确定如何解决此错误.谢谢!

I'm not sure how to resolve this error. Thanks!

推荐答案

我们可以使用 reducetibble

library(purrr)
df1 <- bind_cols(df[1], reduce(df[-1], tibble))
str(df1)
#tibble [3 × 3] (S3: tbl_df/tbl/data.frame)
# $ bears : num [1:3] 1 2 3
# $ talons: num [1:3] 2 3 4
# $ beaks : chr [1:3] "x" "y" "z"

<小时>

或者如果我们需要重命名


Or if we need to rename

library(dplyr)
library(stringr)
df %>%
    select(where(is.tibble)) %>%
    imap_dfc(~  set_names(.x, str_c(.y, '_', names(.x)))) %>%
    bind_cols(df %>%
          select(where(negate(is.tibble))), .)
# A tibble: 3 x 3
#  bears eagles_talons eagles_beaks
#  <dbl>         <dbl> <chr>       
#1     1             2 x           
#2     2             3 y           
#3     3             4 z           

或者使用

df %>%
  reduce(data.frame) 

<小时>

或者更简单的选择是base R

df1 <- do.call(data.frame, df)
str(df1)
#'data.frame':  3 obs. of  3 variables:
# $ bears        : num  1 2 3
# $ eagles.talons: num  2 3 4
# $ eagles.beaks : chr  "x" "y" "z"

这篇关于在数据帧 R 中取消嵌套数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆