我认为我不完全了解嵌套的小对象(数据帧)以及它们与“正常”(即非嵌套的小对象)连接时的行为。
## Create a list and a data frame
ll <- list(matrix(rnorm(4), nrow = 2), matrix(rnorm(4), nrow = 2))
ll
#> [[1]]
#> [,1] [,2]
#> [1,] 1.7299068 0.1577844
#> [2,] 0.7156288 0.6265956
#>
#> [[2]]
#> [,1] [,2]
#> [1,] -0.5285925 1.0423880
#> [2,] -0.1524862 -0.3887486
df <- data.frame("name" = 1:2, "b" = c(0.4, 0.6))
df
#> name b
#> 1 1 0.4
#> 2 2 0.6
# Now I want to:
# 1. Create a nested data frame/tibble.
# 2. Join df and the newely created nested data frame/tibble
#
# There are many ways to create a nested tibble, a convinient one is:
df_nested <- tibble::enframe(ll)
df_nested
#> # A tibble: 2 x 2
#> name value
#> <int> <list>
#> 1 1 <dbl[,2] [2 x 2]>
#> 2 2 <dbl[,2] [2 x 2]>
# looks as expected
# Now when I try to join (merge(), cbind() and other join_* verbs are similar)
dplyr::left_join(df, df_nested, by = "name")
#> name b value
#> 1 1 0.4 1.7299068, 0.7156288, 0.1577844, 0.6265956
#> 2 2 0.6 -0.5285925, -0.1524862, 1.0423880, -0.3887486
由reprex package(v0.3.0)于2019-09-17创建
为什么left_join()
不保留嵌套结构。或不同:什么
加入后必须做些什么来保持嵌套结构?
欢迎都提供一个关于为什么不保留嵌套结构的简单而详尽的答案。
答案 0 :(得分:0)
在连接之前尝试将df
数据帧转换为小标题:
df <- dplyr::as_tibble(df)