【发布时间】:2021-04-10 10:09:46
【问题描述】:
我得到了一个“参考”数据框,它总结了我的主要数据(此处未显示)中的哪些变量应该被过滤以及由哪些值过滤。例如,两个这样的变量是age 和color:
-
age应根据值范围进行过滤 -
color应根据具体值进行过滤。
这是我为 age 和 color 提供的“过滤参考表”的示例:
library(tibble)
library(tidyr)
my_filter_ref_df <-
structure(
list(
var_name = c("age", "colors"),
min = c(18L, NA),
max = c(60L, NA),
values = list(NULL, c("blue", "orange",
"yellow", "purple")),
filtering_type = c("range", "specific")
),
row.names = c(NA,-2L),
class = c("tbl_df", "tbl", "data.frame")
)
## var_name min max values filtering_type
## <chr> <int> <int> <list> <chr>
## 1 age 18 60 <NULL> range
## 2 colors NA NA <chr [4]> specific
## and just to get a sense of the nested data:
my_filter_ref_df %>% unnest_wider(values)
## var_name min max ...1 ...2 ...3 ...4 filtering_type
## <chr> <int> <int> <chr> <chr> <chr> <chr> <chr>
## 1 age 18 60 NA NA NA NA range
## 2 colors NA NA blue orange yellow purple specific
所需输出
my_filter_ref_df 的当前格式不方便。我只想在一列中包含过滤值,因为每一行都与主数据中的不同变量有关。这样,当我需要快速引用此表时,我总是可以使用相同的代码来完成,而不管要查询的变量是什么。
所以我需要 (1) 将 min 和 max 值组合到一个对象,并且 (2) 将该对象嵌套在 values 列中(在 my_filter_ref_df 中,我们已经有一个 values 列)。所以我的目标是输出类似于以下nested_df。
library(purrr)
nested_df <-
structure(
list(
var_name = c("age", "colors"),
values = list(c(min = 18L, max = 60L),
c("blue", "orange", "yellow", "purple")),
filtering_type = c("range",
"specific")
),
row.names = c(NA,-2L),
class = c("tbl_df", "tbl", "data.frame")
)
## # A tibble: 2 x 3
## var_name values filtering_type
## <chr> <list> <chr>
## 1 age <int [2]> range
## 2 colors <chr [4]> specific
> nested_df %>% purrr::chuck("values")
## [[1]]
## min max
## 18 60
## [[2]]
## [1] "blue" "orange" "yellow" "purple"
我的尝试
我看到了类似的已解决问题here。所以我试过这个:
library(dplyr)
my_filter_ref_df %>%
nest(values_2 = c(min, max)) %>%
mutate(values_2 = map(values_2, simplify))
## __????___????__????____????_____????______????____
## | |
## var_name |values filtering_type values_2 ????
## <chr> ↓<list> <chr> <list> |
******** ????
## 1 age *<NULL>* range <int [2]> --|
********
## 2 colors <chr [4]> specific <int [2]>
使用这个 unicode 艺术我试图证明values_2 中的向量(对于age)实际上应该在values 列而不是当前的NULL 列中,而values_2 列不应该存在。
【问题讨论】:
标签: r tidyr nested-lists purrr tibble