我有一個具有以下結構的串列:
l <- list(condition = "AND",
rules = list(list(id = "sex",
field = "sex"),
list(condition = "AND",
rules = list(
list(id = "species",
field = "species"),
list(condition = "AND",
rules = list(
list(id = "bill_length_mm",
field = "bill_length_mm")))))),
valid = TRUE)
我想轉換為這種結構
goal <- list(
list(id = "sex",
field = "sex"),
list(id = "species",
field = "species"),
list(id = "bill_length_mm",
field = "bill_length_mm")
)
該解決方案需要足夠靈活以處理更多/更少的rules元素。任何關于我如何做到這一點的建議將不勝感激!
uj5u.com熱心網友回復:
看起來您可以在這里使用遞回策略。這將查找具有idelemenet 的串列并將它們作為串列回傳。
get_fields <- function (x) {
if (is.list(x)) {
if (!is.null(x$id)) {
return(list(x))
} else {
unname(do.call("c", lapply(x, get_fields)))
}
} else {
NULL
}
}
dput(result<-get_fields(l))
# list(list(id = "sex", field = "sex"), list(id = "species", field = "species"),
# list(id = "bill_length_mm", field = "bill_length_mm"))
uj5u.com熱心網友回復:
使用遞回函式 rrapply
library(rrapply)
out <- rrapply(l, condition = function(x, .xname)
.xname %in% c('id', 'field'), how = "flatten" )
out2 <- unname(split(as.list(out), cumsum(names(out) == "id")) )
- 檢查預期輸出
> identical(goal, out2)
[1] TRUE
或者如評論中提到的@Joris C.
out <- rrapply(l, classes = "list", condition =
function(x) "id" %in% names(x), how = "flatten")
names(out) <- NULL
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/350438.html
