需要帮助创建一个具有均值和标准差的函数。

huangapple go评论59阅读模式
英文:

Need assistance in creating a function with means and standard deviations

问题

我有一个类似的数据集 - 基本上我有两组患者:

df <- structure(list(group = c(1, 1, 1, 2, 2, 2, 2), age = c(45, 67, 
43, 23, 78, 87, 12)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -7L))

这是我写的:

formula <- function(x,y,z,t){
  (x - y) / sqrt((z^2 + t^2)/2)
}

但是,现在我必须手动写函数的四个元素,例如 formula(x,y,z,t)

然而,我想以这种方式转换这个函数:

x <-1的平均年龄
y <-2的平均年龄
z <-1的标准差(年龄)
t <-2的标准差(年龄)

这样,我只需写类似 formula(df$age, df$group) 的内容,它会自动计算正确组中的平均值和标准差,并使用公式。

我是新手写函数,请帮忙。

英文:

I have a dataset like this - basically I have two groups of patients:

df &lt;- structure(list(group = c(1, 1, 1, 2, 2, 2, 2), age = c(45, 67, 
43, 23, 78, 87, 12)), class = c(&quot;tbl_df&quot;, &quot;tbl&quot;, &quot;data.frame&quot;
), row.names = c(NA, -7L))

需要帮助创建一个具有均值和标准差的函数。

This is what I wrote:

formula &lt;- function(x,y,z,t){
  (x - y) / sqrt((z^2 + t^2)/2)
  
}

Right now, I have to manually write all the four elements of the function e.g. formula(x,y,z,t)

However, I would like to transform this function in this way:

x &lt;- mean age of group 1
y &lt;- mean age of group 2
z &lt;- standard deviation (of age) in group 1
t &lt;- standard deviation (of age) in group 2

So that I can simply write something like formula(df$age, df$group) and it automatically calculates mean and standard deviation in the correct group and uses the formula.

I am new to writing functions so please help

答案1

得分: 1

选择属于第一组的 x 值使用 x[group == 1],然后对第二组执行相同操作。然后只需使用您的公式:

formula <- function(x, group){
  treat <- x[group == 1]
  control <- x[group == 2]
  
  (mean(treat) - mean(control)) / sqrt((var(treat) + var(control))/2)
}

formula(df$age, df$group)
[1] 0.05857275
英文:

Select the values of x that belong to the first group with x[group == 1], and do the same for group 2. Then just use your formula:

formula &lt;- function(x, group){
  treat &lt;- x[group == 1]
  control &lt;- x[group == 2]
  
  (mean(treat) - mean(control)) / sqrt((var(treat) + var(control))/2)
}

formula(df$age, df$group)
[1] 0.05857275

huangapple
  • 本文由 发表于 2023年6月13日 07:07:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76460802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定