简体   繁体   中英

How do I apply function to specific columns

I have a sample data frame like the following:

well <- c('A1','A2','A3','A4','A5')
area <- c(21000, 23400, 26800,70000,8000)
length <- c(21, 234, 26,70,22)
group<-c('WT','Control','C2','D2','E1')

data <- data.frame(well,area,length,group)

And I want to apply the function below to remove rows with outliers from the data frame:

Outlier <- function(x){
  low <- median(x, na.rm=TRUE)-5*(mad(x)) 
  high <- median(x, na.rm=TRUE)+5*(mad(x))   
  out <- if_else(x > high, NA,ifelse(x < low, low, x)) 
  out }

How do I apply this function to the dataframe excluding certain columns for example column "well" and "group"?

We can use lapply in base R

data[c('area', 'length')] <- lapply(data[c('area', 'length')], Outlier)

Or with dplyr

library(dplyr) # 1.0.0
data %>% 
     mutate(across(area:length, Outlier))
#    well  area length   group
#1   A1 21000     21      WT
#2   A2 23400     NA Control
#3   A3 26800     26      C2
#4   A4    NA     NA      D2
#5   A5  8000     22      E1

NOTE: Make sure to change the NA to NA_real_ in the 'Outlier' function

Outlier <- function(x){
  low <- median(x, na.rm=TRUE)-5*(mad(x)) 
  high <- median(x, na.rm=TRUE)+5*(mad(x))   
  out <- if_else(x > high, NA_real_,ifelse(x < low, low, x)) 
  out }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM