給定兩個小標題,我想將一個小標題指定為另一個小標題中的一個單元格。但是,當前的方法始終將我的副標題轉換為不同的格式,這會導致錯誤。
我知道我想做的是可能的:
library(dplyr)
desired = tibble(
row = 1:4,
nested = list(
tibble(text = c("a","b","c")),
tibble(numbers = 1:4),
tibble(label = c("high", "med", "low"), value = c(10, 5, 0)),
NA
)
)
此代碼生成一個包含兩列的小標題。第二列包含不同大小和內容的標題。
但是,我無法逐步構建它:
library(dplyr)
# outer tibble
df = tibble(row = 1:4)
# inner tibbles
t1 = tibble(text = c("a","b","c"))
t2 = tibble(numbers = 1:4)
t3 = tibble(label = c("high", "med", "low"), value = c(10, 5, 0))
# setup column of type tibble to assign into
df = df %>%
mutate(nested = purrr::map(row, ~{ tibble() }))
# assign (fails)
df$nested[1] = t1 # no error but df$nested[1] is of type character not tibble
df$nested[2] = t2 # no error but df$nested[2] is of type int not tibble
df$nested[3] = t3 # gives warning and only one column of t3 is assigned
我收到的警告是:
在 df$nested[3] = t3 中:要替換的專案數不是替換長度的倍數
這種方法的結果如下所示:
> df
# A tibble: 4 x 2
row nested
<int> <list>
1 1 <chr [3]>
2 2 <int [4]>
3 3 <chr [3]>
4 4 <tibble [0 × 0]>
如何將(內部)tibbles 分配給現有(外部)tibble 中的單個單元格,以便最終得到 neested tibbles?
uj5u.com熱心網友回復:
使用[[
而不是[
你可以這樣做:
library(dplyr, w = FALSE)
df <- tibble(row = 1:4, nested = vector("list", 4))
df$nested[[1]] <- t1
df$nested[[2]] <- t2
df$nested[[3]] <- t3
df$nested[[4]] <- NA
df
#> # A tibble: 4 × 2
#> row nested
#> <int> <list>
#> 1 1 <tibble [3 × 1]>
#> 2 2 <tibble [4 × 1]>
#> 3 3 <tibble [3 × 2]>
#> 4 4 <lgl [1]>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/535403.html
標籤:rdplyr小题大做
上一篇:根據R中匹配列的長度重復串列