0

df给定在函数中获得的 data.frame myfunc,如何在函数中添加更多列df

如果在函数之外手动完成,它可以工作:

require("broom")

myfunct <- function(mylabel1, mylabel2){

  df <- broom::glance(t.test(extra ~ group, data = sleep))

  # df$lab1 <- mylabel1
  # df$lab2 <- mylabel2
}

result <- myfunct(mylabel1 = "AA", mylabel2 = "BB")
mylabel1 = "AA"
mylabel2 = "BB"
result$lab1 <- mylabel1
result$lab2 <- mylabel2

> result
  estimate estimate1 estimate2 statistic    p.value parameter  conf.low conf.high                  method alternative lab1 lab2
1    -1.58      0.75      2.33 -1.860813 0.07939414  17.77647 -3.365483 0.2054832 Welch Two Sample t-test   two.sided   AA   BB

但是在创建新变量时不会myfunc

myfunct <- function(mylabel1, mylabel2){

  df <- broom::glance(t.test(extra ~ group, data = sleep))

  df$lab1 <- mylabel1
  df$lab2 <- mylabel2
}

result <- myfunct(mylabel1 = "AA", mylabel2 = "BB")

> result
[1] "BB"

PD:这是一个包含多个结果的更复杂函数所面临的问题的最小可重复示例。

4

0 回答 0