在 R 中的 for 循环中使用 if else{} 组合数据集

combine dataset using if else{} in for loop in R

我需要一个函数来删除两个以上的因子值,在本例中为 cyl。必须取数值的平均值和因子值的 prop.table()=1。最后,它应该创建一个数据集作为预期的答案。非常感谢。

`head(mtcars)
    mtcars$vs <- as.factor(mtcars$vs) 
    mtcars$cyl <- as.factor(mtcars$cyl) # sholuld be removed from the final dataset
    #var <- colnames(mtcars); var
    Summ.Continuous <- tab.prob <- out <- NULL
    
    myfunction <- function(var,df) {
      
      df <- df[, !sapply(df, is.character)] #Remove Character Columns
      
      for (j in 1:ncol(df)) {
        if(is.factor(df[,j])){ 
          tab.prob[j] <- prop.table(table(df[,j]))
          
        } else {
          Summ.Continuous[j] <- describe(df)$mean
          
        }} 
      out <- list(tab.prob, Summ.Continuous)
      return(out)}
    
    myfunction(var, mtcars)

预期答案

  mp 20.09 
    cyl NA 
    disp 230.7 
    hp 146.7  
    drat 3.597 
    wt 3.217 
    qsec 17.85 
    vs 0.4375 #prob.table based on 1
    am 0.4062 
    gear 3.688 
    carb 2.812 `

使用tidyverse我们可以使用where有条件地select,使用across有条件地总结,例如:

library(tidyverse)
mtcars %>%
  mutate(vs = as.factor(vs),
         cyl = as.factor(cyl)) %>%
  select(!where(~ is.factor(.x) && levels(.x) > 2)) %>%
  summarise(across(where(is.numeric), mean),
            across(where(is.factor), ~ prop.table(table(.x))[2]))

       mpg     disp       hp     drat      wt     qsec      am   gear   carb     vs
1 20.09062 230.7219 146.6875 3.596563 3.21725 17.84875 0.40625 3.6875 2.8125 0.4375

这可以与 tidylog 包一起使用,以告知每个步骤发生了什么,这里有助于通知 cyl 已从输出中删除。

library(tidylog)
~ previous code here

mutate: converted 'cyl' from double to factor (0 new NA)
        converted 'vs' from double to factor (0 new NA)
select: dropped one variable (cyl)
summarise: now one row and 10 columns, ungrouped