【问题标题】:Using paste() within t.test() in user defined R function在用户定义的 R 函数中使用 t.test() 中的 paste()
【发布时间】:2018-02-24 18:20:38
【问题描述】:

我正在尝试编写一个函数,该函数接受来自用户的 Var1Var2 并运行 t.test 并返回女性分类的平均值。但是我收到了 calc 行的错误。如果我在没有粘贴和as.formula 函数的情况下运行程序并使用t.test(dat[[Var2]]~dat[[Var1]] 运行,我会得到正确的答案。

但在我的原始代码中,我需要使用粘贴功能。谁能让我知道下面代码中使用 paste 和 as.formula 函数的错误是什么?我正在使用 MASS 库中的 quine 数据框。

func = function(dat=quine,Var1,Var2){
  # calc = t.test(dat[[Var2]]~dat[[Var1]] #gives the answer
  calc = t.test(as.formula(paste(dat[[Var2]], dat[[Var1]], sep="~"))) #gives an error
  return(F.mean = calc$estimate[1])
}

func(Var1= "Sex", Var2= "Days")

这是头(奎因)

Eth Sex Age Lrn Days

1 A M F0 SL 2

2 A M F0 SL 11

3 A M F0 SL 14

4 A M F0 AL 5

5 A M F0 AL 5

6 A M F0 AL 13

【问题讨论】:

  • 您可以使用dput(quine) 发布示例数据集吗?或者如果数据框太大,dput(head(quine, 20)).

标签: r function user-defined


【解决方案1】:

这应该可行:

func <- function(dat = quine, Var1, Var2){
  calc = t.test(as.formula(paste("dat[[Var2]]", "dat[[Var1]]", sep = "~"))) 
  return(F.mean = calc$estimate[1])
}

func(Var1 = "Sex", Var2 = "Days")

注意粘贴字符串和对象的区别。

【讨论】:

    【解决方案2】:

    在函数中包含代码行

    print(paste(dat[[Var2]], dat[[Var1]], sep="~"))
    

    看看有什么问题。 paste 将向量 dat[[Var1]] 的每个元素与向量 dat[[Var2]] 的每个元素粘贴在一起。结果是一个长度为nrow(dat) 的向量。然后,只有 first 元素被强制转换为 formulat.test 只使用了那个。

    正确的代码是(注意data 参数):

    func = function(dat=quine,Var1,Var2){
      # calc = t.test(dat[[Var2]]~dat[[Var1]] #gives the answer
      calc = t.test(as.formula(paste(Var2, Var1, sep="~")), data = dat)
      return(c(F.mean = unname(calc$estimate[1])))
    }
    

    还要注意return 指令的变化。

    虽然我们没有样本数据来测试这个功能,但我们可以弥补一些东西。

    set.seed(8294)
    n <- 100
    quine <- data.frame(Sex = sample(c("M", "F"), n, TRUE), Days = runif(n))
    
    func(Var1= "Sex", Var2= "Days")
    #   F.mean 
    #0.5100037
    

    【讨论】:

    • 谢谢。 unname() 函数在代码的另一部分有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多