【问题标题】:Custom function to check the data type of each column自定义函数检查每列的数据类型
【发布时间】:2021-06-15 12:47:08
【问题描述】:

我正在创建一个贯穿我的变量并确定它们是否为数字的函数。如果变量是数字,我希望它打印均值、中位数、方差、众数和范围。如果它不是数字,我希望它只打印模式。但是不确定我是否使用了正确的功能(typeof & class)

我收到以下错误

Error: Must group by variables found in `.data`.
* Column `col` is not found.

我的尝试(功能)

myfun <- function(df,col) {

  print(typeof(df[,col]))
   if(class(df$col)=="numeric"){
     mean=mean(df$col)
     median=median(df$col)
     variance=var(df$col)
     mode =mode(df$col)
     range=range(df$col)
     df <- data.frame(mean=mean,median=median,variance=variance,mode=mode,range=range)
   } else df=count(df,col,sort=TRUE)[1,1]
     print(max_count)
 }

myfun(iris,"Species")
myfun(iris,"Sepal.Length")

【问题讨论】:

  • 我猜你想使用count(df,!!col,sort=TRUE)。我推荐阅读Advanced R

标签: r function dplyr tidyverse


【解决方案1】:

不要在函数内部使用$,我们可以使用[[ 来提取特定的列。

可以如下修改函数-

myfun <- function(df,col) {

  if(is.numeric(df[[col]])) {
    list(mean=mean(df[[col]]),
         median=median(df[[col]]),
         variance = var(df[[col]]),
         mode = Mode(df[[col]]),
         range=range(df[[col]]))
  } else list(mode = Mode(df[[col]]))
}


Mode <- function(x) {
  ux <- unique(x)
  ux[which.max(tabulate(match(x, ux)))]
}

myfun(iris,"Species")

#$mode
#[1] setosa
#Levels: setosa versicolor virginica

myfun(iris,"Sepal.Length")
#$mean
#[1] 5.843333

#$median
#[1] 5.8

#$variance
#[1] 0.6856935

#$mode
#[1] 5

#$range
#[1] 4.3 7.9

【讨论】:

  • 不要在函数内部使用 $,我们可以使用 [[ 来提取特定的列。只是我需要的建议。谢谢
猜你喜欢
  • 1970-01-01
  • 2020-03-23
  • 2014-08-05
  • 2021-02-15
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 2012-04-21
  • 1970-01-01
相关资源
最近更新 更多