我想創建一個列,它是一個小標題串列(具有不同的行號)。直截了當的方法失敗了。例子:
> x <- data.frame('a' = 1:2,
'b' = list(tibble('c' = 1:4, 'd' = 1:4),
tibble('c' = 1:3, 'd' = 1:3)))
Error in (function (..., row.names = NULL, check.rows = FALSE, check.names = TRUE, :
arguments imply differing number of rows: 4, 3
我可以通過用I. 但是,當我這樣做并嘗試取消嵌套時,我不能。
> x <- data.frame('a' = 1:2,
'b' = I(list(tibble('c' = 1:4, 'd' = 1:4),
tibble('c' = 1:3, 'd' = 1:3))))
> x %>% unnest(cols = b)
# A tibble: 2 x 2
a b
<int> <I<list>>
1 1 <tibble [4 x 2]>
2 2 <tibble [3 x 2]>
如何創建一個作為 tibble 串列的列,稍后我可以取消嵌套?
uj5u.com熱心網友回復:
tibble使用s 而不是s創建串列列要容易得多data.frame(請參見 Hadley 在此處的注釋)。
data.frame()您可以通過從to切換來修復您的代碼tibble():
library(dplyr)
x <- tibble(
'a' = 1:2,
'b' = list(
tibble('c' = 1:4, 'd' = 1:4),
tibble('c' = 1:3, 'd' = 1:3)
)
)
x
#> # A tibble: 2 × 2
#> a b
#> <int> <list>
#> 1 1 <tibble [4 × 2]>
#> 2 2 <tibble [3 × 2]>
x %>% tidyr::unnest(b)
#> # A tibble: 7 × 3
#> a c d
#> <int> <int> <int>
#> 1 1 1 1
#> 2 1 2 2
#> 3 1 3 3
#> 4 1 4 4
#> 5 2 1 1
#> 6 2 2 2
#> 7 2 3 3
由reprex 包于 2022-03-31 創建(v2.0.1)
uj5u.com熱心網友回復:
您可以先創建沒有 list-column 的 data.frame 并添加串列:
x <- data.frame(a = 1:2)
x$b <- list(tibble('c' = 1:4, 'd' = 1:4),
tibble('c' = 1:3, 'd' = 1:3)
)
控制:
str(x)
# 'data.frame': 2 obs. of 2 variables:
# $ a: int 1 2
# $ b:List of 2
# ..$ : tibble [4 x 2] (S3: tbl_df/tbl/data.frame)
# .. ..$ c: int 1 2 3 4
# .. ..$ d: int 1 2 3 4
# ..$ : tibble [3 x 2] (S3: tbl_df/tbl/data.frame)
# .. ..$ c: int 1 2 3
# .. ..$ d: int 1 2 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/453422.html
上一篇:以鍵為索引的字典到資料框
