英文:
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 <- 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))
This is what I wrote:
formula <- 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 <- mean age of group 1
y <- mean age of group 2
z <- standard deviation (of age) in group 1
t <- 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 <- 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论