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

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

提问人:Seyma Kalay 提问时间:1/30/2022 更新时间:1/30/2022 访问量:61

问:

我需要一个函数来删除两个以上的因子值,在本例中为 .必须取数值和 for 因子值的平均值。最后,它应该创建一个数据集作为预期的答案。提前非常感谢。cylprop.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 `
r for循环 语句 tidyr 操作

评论

0赞 Donald Seinen 1/30/2022
你如何获得 VS?0.4
1赞 Seyma Kalay 1/30/2022
prop.table(table(mtcar$vs)) = 1

答:

1赞 Donald Seinen 1/30/2022 #1

using 我们可以有条件地选择 using ,并有条件地使用 进行总结,例如:tidyversewhereacross

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

这可以与包一起使用,以通知每个步骤中发生的情况,此处用于通知已从输出中删除的内容。tidylogcyl

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

评论

0赞 Seyma Kalay 1/30/2022
非常感谢,但我想知道是否有办法保持名称顺序?
0赞 Donald Seinen 1/30/2022
我不确定你说的名字顺序是什么意思......?
0赞 Seyma Kalay 1/30/2022
QSec 与 AM。就像 Colnames(MTCARS) 的变化一样。有没有解决此问题的选项?不过这并不重要。