简体   繁体   中英

How to loop through columns in R and apply different functions based on column names

I want to loop through each columns in the data frame and apply the functions on each column based on the column name if a column name is abc then i want the my.summary() function to be effected in that column and remaining columns should use the other function

 x <- sapply(Data, as.numeric )
 x[is.na(x)] <- 0

  my.summary <- function(a){
  c(
  Worst_Decile = quantile(a,0.10),
  Worst_Quartile = quantile(a,0.25),
  median = median(a),
  Best_Quartile = quantile(a,0.75),
  Best_Decile = quantile(a,0.90)
   )
   }
 LowIsBetter <- function(a){
  c(
  Worst_Decile = quantile(a,0.90),
  Worst_Quartile = quantile(a,0.75),
  median = median(a),
  Best_Quartile = quantile(a,0.25),
  Best_Decile = quantile(a,0.10)
  )
 }

 for (i in colnames(x)){
 if(i == "ABC"){
 xy <- apply(x,2,my.summary)
 }else{xy <- apply(x,2,LowIsBetter)}
  }

Data frame:

在此处输入图像描述

Expected result:

在此处输入图像描述

Try this:

result <- sapply(colnames(x), function(col) {
  if(col == 'abc') my.summary(x[, col])
  else LowIsBetter(x[, col])
})

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