【问题标题】:How to create an R function that takes two inputs?如何创建一个接受两个输入的 R 函数?
【发布时间】:2020-02-24 07:47:16
【问题描述】:

我被分配了一个家庭作业问题:

Write a function called numeric_summary which takes two inputs:\
`x`: A numeric vector\
`group`: A factor vector of the same length as x
and produces a list as output which contains the following elements:\
`missing`: The number of missing values in x\
`means`: The means of x for each level of groups.\
`sds`: The standard deviations of x for each level of groups\
`p.value`: The p-value for a test of the hypothesis that the means across the >levels of groups are the same (versus the two-sided alternative)\
`is.binary`: Set to FALSE for for this function

目前我并不关心创建输出列表,但我不确定如何对两个输入方面进行编码,尤其是在它们是两种不同类型的情况下。有一个例子:

#numeric_summary <- function(x, group){} 
#
# for example:
#numeric_summary(titanic4$age, titanic4$pclass)

我认为该功能应该适用于任何分配的 x 和组,所以我的困难在于使该方面模块化或可以这么说。使用的包是tidyversePASWRknitr

【问题讨论】:

    标签: r list function variables input


    【解决方案1】:

    我们可以创建一个类似的函数

    numeric_summary <- function(x, group) {
           #Count missing values
      list(missing = sum(is.na(x)), 
           #Mean by group
           means = tapply(x, group, mean),
           #SD by group 
           sds = tapply(x, group, sd))
    }
    
    numeric_summary(mtcars$mpg, mtcars$cyl)
    #$missing
    #[1] 0
    
    #$means
    #    4     6     8 
    #26.66 19.74 15.10 
    
    #$sds
    #    4     6     8 
    #4.510 1.454 2.560 
    

    【讨论】:

    • 谢谢!快速提问,为什么我们要使用函数 tapply 而不是 apply?
    • @GianBatayola 因为apply 没有考虑计算中的组。它按行或按列执行计算。
    猜你喜欢
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-10-04
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多