如何循环遍历 R 中的列并根据列名应用不同的函数

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

我想遍历数据框中的每一列,并根据列名在每一列上应用函数,如果列名是 abc 那么我希望 my.summary() 函数是在该列中生效,其余列应使用其他函数

 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)}
  }

数据框:

预期结果:

试试这个:

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