gpt4 book ai didi

r - 有没有办法生成类似于 mutate_at 或 mutate_if 的 Gather_at 或 Gather_if 函数

转载 作者:行者123 更新时间:2023-12-02 09:10:06 24 4
gpt4 key购买 nike

我认为标题相当简单。但只是提供一些数据和示例:

test <- tibble(
ID1 = letters,
ID2 = LETTERS,
A1 = runif(26),
B1 = runif(26),
A2 = runif(26),
B2 = runif(26)
)

是否有一种方法可以使用简单命令仅收集数字列,例如:

test %>% gather_if(is.numeric, 'key', 'value')

?这将给出与以下相同的输出:

> test %>% gather('key', 'value', -ID1, -ID2)
# A tibble: 104 x 4
ID1 ID2 key value
<chr> <chr> <chr> <dbl>
1 a A A1 0.558
2 b B A1 0.0614
3 c C A1 0.999
4 d D A1 0.854
5 e E A1 0.463
6 f F A1 0.875
7 g G A1 0.796
8 h H A1 0.484
9 i I A1 0.336
10 j J A1 0.191
# ... with 94 more rows

查看聚集函数:

> gather
function (data, key = "key", value = "value", ..., na.rm = FALSE,
convert = FALSE, factor_key = FALSE)
{
UseMethod("gather")
}
<bytecode: 0x000000001b71ff18>
<environment: namespace:tidyr>

修改它似乎并不那么直接(至少对于我这样一个半新的 R 用户来说不是)。

编辑:

我在 dplyr 中选择的词汇可能不完全准确。但我认为 MWE 很好地解释了我想要什么类型的函数。

编辑2:

使用 bschneidr 的答案,可以通过以下方式完成此临时版本。

gather_if <- function(data, fun, key, value, ..., na.rm = FALSE, convert = 
FALSE, factor_key = FALSE){
data %>%
gather(!!key, !!value, select_if(., fun) %>% colnames(), ...,
na.rm = FALSE, convert = FALSE, factor_key = FALSE)
}

这给出:

> test %>% gather_if(is.numeric, 'key', 'value')
# A tibble: 104 x 4
ID1 ID2 key value
<chr> <chr> <chr> <dbl>
1 a A A1 0.558
2 b B A1 0.0614
3 c C A1 0.999
4 d D A1 0.854
5 e E A1 0.463
6 f F A1 0.875
7 g G A1 0.796
8 h H A1 0.484
9 i I A1 0.336
10 j J A1 0.191
# ... with 94 more rows

最佳答案

我认为 tidyr 正在开发一个 gather_if 函数(请参阅 tidyr 的 Github 存储库上的 this pull request)。

目前,我认为最简单的方法是在 gather 调用中使用 dplyr 的 select_if 函数。

test %>% 
gather('key', 'value',
colnames(select_if(., is.numeric)))

关于r - 有没有办法生成类似于 mutate_at 或 mutate_if 的 Gather_at 或 Gather_if 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53415303/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com