![](/img/trans.png)
[英]how to expand the dplyr::tibble with the column contain list of list?
[英]How to expand rows in a tibble based on a list of values
我有這一行
first coor second
<chr> <chr> <chr>
1 first ALL second
我想將此行擴展為多行並根據以下值替換 coor 列
coor = c("ESP", "FRA", "GER")
所以我最終得到了這個
first coor second
<chr> <chr> <chr>
1 first ESP second
2 first FRA second
3 first GER second
有任何想法嗎?
另一種選擇是:
slice
將 dataframe 擴展為向量的長度coor
library(dplyr)
vec_coor <- coor
dat %>%
slice(rep(1:n(), each = length(vec_coor))) %>%
mutate(coor = vec_coor)
first coor second
<chr> <chr> <chr>
1 first ESP second
2 first FRA second
3 first GER second
我們可以創建一個list
列並將其unnest
library(dplyr)
library(tidyr)
dat %>%
mutate(coor = list(.env$coor)) %>%
unnest(coor)
-輸出
# A tibble: 3 × 3
first coor second
<chr> <chr> <chr>
1 first ESP second
2 first FRA second
3 first GER second
或者另一種選擇是使用“coor”向量crossing
數據子集
crossing(dat %>%
select(-coor), coor)
# A tibble: 3 × 3
first second coor
<chr> <chr> <chr>
1 first second ESP
2 first second FRA
3 first second GER
dat <- tibble(first = "first", coor = "ALL", second = "second")
coor <- c("ESP", "FRA", "GER")
另一個解決方案:
library(tidyverse)
df <- data.frame(
stringsAsFactors = FALSE,
first = c("first"),
coor = c("ALL"),
second = c("second")
)
df %>%
complete(first, coor=c("ESP", "FRA", "GER"), second) %>% filter(!coor == "ALL")
#> # A tibble: 3 × 3
#> first coor second
#> <chr> <chr> <chr>
#> 1 first ESP second
#> 2 first FRA second
#> 3 first GER second
這是另一種選擇。 我們可以創建一個查找表並應用full_join
。 dat
和coor
來自 akrun 的回答。
library(tidyverse)
lookup <- data.table(
coor = rep("ALL", length(coor)),
coor_new = coor
)
dat2 <- dat %>%
full_join(lookup, by = "coor") %>%
select(first, coor = coor_new, second)
dat2
# # A tibble: 3 x 3
# first coor second
# <chr> <chr> <chr>
# 1 first ESP second
# 2 first FRA second
# 3 first GER second
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.