gpt4 book ai didi

r - purrr::map_if:仅将函数应用于特定列

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

直到现在,当我只想将一个函数应用于数字列时,我使用

library(tidyverse)

map(diamonds[map_lgl(diamonds, is.numeric)], range, na.rm = TRUE)

现在我想知道在这种情况下 map_if() 是否会不那么笨拙。我试过的是这样的:

map_if(diamonds, is.numeric, range, na.rm = TRUE)

但出于某种原因,range 现在是为所有列计算的,而不仅仅是数字列。

我是做错了什么还是误解了 map_if() 的用途?如果是后者,我会在什么情况下使用 map_if()

最佳答案

我们可以用 summarise_if 来做到这一点

diamonds %>% 
summarise_if(is.numeric, funs(list(range(.)))) %>%
unnest
# A tibble: 2 x 7
# carat depth table price x y z
# <dbl> <dbl> <dbl> <int> <dbl> <dbl> <dbl>
# 1 0.200 43.0 43.0 326 0 0 0
#2 5.01 79.0 95.0 18823 10.7 58.9 31.8

map_if 将应用于 numeric 列上的函数,并保持其他列不变,以便我们从这些列中获取原始值。 summarise_if 将根据条件对数据集进行子集化,并将函数应用于这些列

关于r - purrr::map_if:仅将函数应用于特定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49190307/

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