【问题标题】:How to loop through columns in R and apply different functions based on column names如何遍历 R 中的列并根据列名应用不同的函数
【发布时间】:2020-12-08 12:00:42
【问题描述】:

如果列名是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)}
  }

数据框:

预期结果:

【问题讨论】:

  • 你能分享你的数据框和预期结果的代码而不是图像吗?

标签: r rscript


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-28
    相关资源
    最近更新 更多