在数据帧 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")
)
我曾尝试使用 unnest
和 unnest_wider
、flatten
和 unlist
但都无济于事.例如,如果我运行,
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!
答
我们可以使用 reduce
和 tibble
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"