英文:
Assistance in creating formula to replace variables
问题
I have a dataset like this:
db <- structure(list(group = c(1, 1, 1, 2, 2, 2, 2), female = c(1,
0, 1, 1, 1, 0, 1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-7L))
Where female=1 means that the patient is female, female=0 means is male.
Then, I have this formula.
Suppose x=frequency of females in group 1, y=frequency of females in group 2 [which I calculated manually]
formula <- function(x,y){
x <- x/100 #frequency should not be expressed as percentage but :100
y <- y/100
z <- x*(1-x)
t <- y*(1-y)
k <- sum(z,t)
l <- k/2
return((x-y)/sqrt(l))
}
Instead of writing manually the frequency, for example, of females in group 1 (x) and in group 2 (y), I would like to change this function so that I can write something like:
formula(db$female, db$group)
and automatically in this formula R calculates the frequency of females and uses it in the formula
英文:
I have a dataset like this:
db <- structure(list(group = c(1, 1, 1, 2, 2, 2, 2), female = c(1,
0, 1, 1, 1, 0, 1)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-7L))
Where female=1 means that the patient is female, female=0 means is male.
Then, I have this formula.
Suppose x=frequency of females in group 1, y=frequency of females in group 2 [which I calculated manually]
formula <- function(x,y){
x <- x/100 #frequency should not be expressed as percentage but :100
y <- y/100
z <- x*(1-x)
t <- y*(1-y)
k <- sum(z,t)
l <- k/2
return((x-y)/sqrt(l))
}
Instead of writing manually the frequency, for example, of females in group 1 (x) and in group 2 (y), I would like to change this function so that I can write something like:
formula(db$female, db$group)
and automatically in this formula R calculates the frequency of females and uses it in the formula
答案1
得分: 1
根据问题描述,我稍微修改了这个函数,应该按描述的方式工作,前提是分组要么是1要么是2。
formula <- function(input1, input2){
x <- sum(input1[input2 == 1]) / length(input1[input2 == 1])
y <- sum(input1[input2 == 2]) / length(input1[input2 == 2])
x <- x/100 #频率不应该表示为百分比,而是:100
y <- y/100
z <- x*(1-x)
t <- y*(1-y)
k <- sum(z,t)
l <- k/2
return((x-y)/sqrt(l))
}
由于x
和y
出现多次,为了避免混淆,我已将函数的参数更改为input1
和input2
。
英文:
Based on the description of the problem, I have slightly modified the function, this should work as described, provided the groups are either 1 or 2.
formula <- function(input1, input2){
x <- sum(input1[input2 == 1]) / length(input1[input2 == 1])
y <- sum(input1[input2 == 2]) / length(input1[input2 == 2])
x <- x/100 #frequency should not be expressed as percentage but :100
y <- y/100
z <- x*(1-x)
t <- y*(1-y)
k <- sum(z,t)
l <- k/2
return((x-y)/sqrt(l))
}
Due to x
and y
appearing multiple times, and to avoid confusion, I have changed the arguments of the function to input1
and input2
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论