我觉得应该有一种有效的方法来dplyr使用case_whenand 来改变新列contains,但是无法让它工作.
我理解使用case_when内部mutate是"有点实验性"(如本文所述),但对任何建议都会感激不尽.
不起作用:
library(tidyverse)
set.seed(1234)
x <- c("Black", "Blue", "Green", "Red")
df <- data.frame(a = 1:20,
b = sample(x,20, replace=TRUE))
df <- df %>%
mutate(group = case_when(.$b(contains("Bl")) ~ "Group1",
case_when(.$b(contains("re", ignore.case=TRUE)) ~ "Group2")
)
Run Code Online (Sandbox Code Playgroud) 我搜索过类似的问题,但无法找到所需的确切解决方案.这个问题有点类似,但只涉及总结多个连续变量的问题,而不是因素.
我有一个数据帧由4个因子变量(sex,agegroup,hiv,group),例如
set.seed(20150710)
df<-data.frame(sex=as.factor(c(sample(1:2, 10000, replace=T))),
agegroup=as.factor(c(sample(1:5,10000, replace=T))),
hiv=as.factor(c(sample(1:3,10000, replace=T))),
group=as.factor(c(sample(1:2,10000, replace=T)))
)
levels(df$sex)<- c("Male", "Female")
levels(df$agegroup)<- c("16-24", "25-34", "35-44", "45-54", "55+")
levels(df$hiv)<-c("Positive", "Negative", "Not tested")
levels(df$group)<-c("Intervention", "Control")
Run Code Online (Sandbox Code Playgroud)
我想创建一个汇总表,给出每个级别的暴露变量的计数和比例sex,agegroup并按hiv层次分层group.
编辑:这是我的目标:
X N_Control Percent_Control N_Intervention Percent_Intervention
1 sex_Female 2517 0.5041057 2480 0.4953066
2 sex_Male 2476 0.4958943 2527 0.5046934
3 agegroup_16-24 1005 0.2012818 992 0.1981226
4 agegroup_25-34 1001 0.2004807 996 0.1989215
5 agegroup_35-44 1010 …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用tidyeval进行编程。
我想编写一个函数为选定的结果变量运行逻辑回归模型:
library(tidyverse)
set.seed(1234)
df <- tibble(id = 1:1000,
group = sample(c("Group 1", "Group 2", "Group 3"), 1000, replace = TRUE),
died = sample(c(0,1), 1000, replace = TRUE))
myfunc <- function(data, outcome){
enquo_var <- enquo(outcome)
fit <- tidy(glm(!!enquo_var ~ group, data=data,
family = binomial(link = "logit")),
exponentiate = TRUE, conf.int=TRUE)
fit
}
myfunc(df, died)
Run Code Online (Sandbox Code Playgroud)
但是得到:
!enquo_outcome错误:参数类型无效
(请注意,实际情况涉及更复杂的功能)。
这可能吗?