问题描述
实际上,在尝试 this problem 时,我遇到了一个奇怪的情况,即 baseR 的 if() else()
按预期工作,但 ifelse
和 if_else
都没有工作。让我在这里重新表述实际问题。
向量中的值将在集合操作 union
上累加,直到唯一计数达到 >3,在这种情况下它会重置。因此,对于一个 df 说 y
与单列 a
,预期的结果是-
y <- data.frame(a=c(1,2,3,4,5,6,7,9,8))
y
a b
1 1 1
2 2 1,2
3 2 1,2
4 3 1,3
5 3 1,3
6 4 4
7 3 4,3
8 2 4,2
9 2 4,2
10 5 5
11 6 5,6
12 7 5,7
13 9 9
14 8 9,8
现在的问题是,基础 R 的 if() else ()
正在 purrr::accumulate 内工作,而 if_else
和 ifelse
都没有工作!谁能详细说明原因?
y <- data.frame(a=c(1,8))
y
#> a
#> 1 1
#> 2 2
#> 3 2
#> 4 3
#> 5 3
#> 6 4
#> 7 3
#> 8 2
#> 9 2
#> 10 5
#> 11 6
#> 12 7
#> 13 9
#> 14 8
library(tidyverse)
#this works
accumulate(y$a,~if(length(union(.x,.y)) == 4) .y else union(.x,.y))
#> [[1]]
#> [1] 1
#>
#> [[2]]
#> [1] 1 2
#>
#> [[3]]
#> [1] 1 2
#>
#> [[4]]
#> [1] 1 2 3
#>
#> [[5]]
#> [1] 1 2 3
#>
#> [[6]]
#> [1] 4
#>
#> [[7]]
#> [1] 4 3
#>
#> [[8]]
#> [1] 4 3 2
#>
#> [[9]]
#> [1] 4 3 2
#>
#> [[10]]
#> [1] 5
#>
#> [[11]]
#> [1] 5 6
#>
#> [[12]]
#> [1] 5 6 7
#>
#> [[13]]
#> [1] 9
#>
#> [[14]]
#> [1] 9 8
# While these didn't
accumulate(y$a,~ifelse(length(union(.x,.y)) == 4,.y,union(.x,.y)))
#> [1] 1 1 1 1 1 1 1 1 1 1 1 1 1 1
accumulate(y$a,~if_else(length(union(.x,.y)))
#> Error: `false` must be length 1 (length of `condition`),not 2.
由 reprex package (v2.0.0) 于 2021 年 5 月 14 日创建
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)