将功能应用于R数据框的每个组和列 [英] Applying function to each group and column of R dataframe
本文介绍了将功能应用于R数据框的每个组和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要应用此功能
replace_outliers <- function(column) {
qnt <- quantile(column, probs=c(.25, .75))
upper_whisker <- 1.5 * IQR(column)
clean_data <- column
clean_data[column > (qnt[2] + upper_whisker)] <- median(column)
clean_data
}
到看起来像这样的数据集:
to dataset that look like this:
Category a b c
a 2.0 5.0 -5.0
a 1.5 10.0 10.0
b 3.2 14.5 100.2
... ... ... ...
我必须对每个类别和每个列分别应用 replace_outliers
。
I have to apply replace_outliers
to each category apart and for each column. How to achieve that?
推荐答案
您可以使用软件包 dplyr
。使用 group_by
对每个类别执行此操作,并使用 mutate_if
将函数应用于所有数字列
You can use the package dplyr
. Use group_by
to do it for each Category and mutate_if
to apply the function to all numerical columns
library(dplyr)
df <- read.table(header = TRUE, text =
" Category a b c
a 2.0 5.0 -5.0
a 1.5 10.0 10.0
b 3.2 14.5 100.2")
replace_outliers <- function(column) {
qnt <- quantile(column, probs=c(.25, .75))
upper_whisker <- 1.5 * IQR(column)
clean_data <- column
clean_data[column > (qnt[2] + upper_whisker)] <- median(column)
clean_data
}
df %>% group_by(Category) %>%
mutate_if(is.numeric, replace_outliers)
这篇关于将功能应用于R数据框的每个组和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文