我對地圖有一個奇怪的問題。我的目標是為每個元素回傳一個串列。以元素為條件,我想要一個不同長度的串列(或至少應用不同的邏輯)。這似乎非常困難,并且 map 正在回傳各種值(見下文):
map(1:2, ~ list(.x, .x 1))
# returns list(list(1,2), list(2,3)
map(1:2, ~ ifelse(.x > 1,
list(.x, .x 1),
list(.x, .x)))
# returns list(list(1), list(2))
map(1:2, ~ case_when(.x > 1 ~ list(.x, .x 1),
TRUE ~ list(.x)))
# returns list(list(1,1), list(2,3)
我找到了兩種方法來解決這個問題:
# Add a list around it and then remove the list
map(1:2, ~ ifelse(.x > 1,
list(list(.x, .x 1)),
list(.x))) %>%
map(., ~.[[1]])
# Use a two step map_if
map_if(1:2, ~.x > 1,
~list(.x, .x 1)) %>%
map_if(is.integer, ~list(.x))
兩者都讓我覺得有點奇怪..這方面的最佳做法是什么?
uj5u.com熱心網友回復:
我們可以使用if/else代替ifelse或case_when因為這些要求所有引數的長度相同(除非我們rep找到) i.e. the 測驗長度` is of1
library(purrr)
map(1:2, ~ if(.x > 1) list(.x, .x 1) else list(.x, .x))
-輸出
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 1
[[2]]
[[2]][[1]]
[1] 2
[[2]][[2]]
[1] 3
注意:這里向量中的每個元素都是回圈的,因此我們不需要ifelse. 如果我們仍然想使用它,請使用ifelse回圈的元素執行并包裝輸出list
map(1:2, ~ list(.x, ifelse(.x > 1,
.x 1,
.x)))
-輸出
[[1]]
[[1]][[1]]
[1] 1
[[1]][[2]]
[1] 1
[[2]]
[[2]][[1]]
[1] 2
[[2]][[2]]
[1] 3
uj5u.com熱心網友回復:
像這樣的東西怎么樣:
library(tidyverse)
map(1:2, \(x) {test <- list(x, ` `(x > 1) x); test[!duplicated(test)]})
#> [[1]]
#> [[1]][[1]]
#> [1] 1
#>
#>
#> [[2]]
#> [[2]][[1]]
#> [1] 2
#>
#> [[2]][[2]]
#> [1] 3
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/520920.html
上一篇:根據R中列的值分解行
下一篇:選擇n列中的日期匹配的行
