我有一个数据集,它看起来如下(有大约200个人)。
NAME AGE2012 SEX SurveyDate12 WAZ12 BAZ12 HAZ12 HB12 SurveyDate14 WAZ14 BAZ14 HAZ14 HB14
1 22 Male 2012-11-26 -1.2 -0.54 -0.01 11.9 2014-11-26 -1.5 -0.52 -0.43 12.2
2 26 Female 2012-11-26 -1.5 -0.36 -0.04 11.2 2014-11-26 -1.7 -0.84 -0.32 11.4
我目前正在用他们做一个斜图 所以我必须对这个数据集做一些事情 比如使用pivot长。我正在练习使用因子,所以试图将我所做的一切都保持在一个函数内。我的代码可以只用HB来做图(见下文)。但我想做的是让这段代码适用于我在数据集中的所有4个变量,只是使用函数。谁能帮我解决这个问题?
slopegraph_prep <- function(health_longer, HB){health %>%
select(NAME:SEX, starts_with("HB")) %>%
pivot_longer(cols = starts_with("HB"),
names_to = "Year",
names_prefix = "HB",
values_to = "HB") %>%
mutate(
HB = case_when(
HB < 0 ~ "NA",
TRUE ~ as.character(HB)
)
) %>%
na_if("NA") %>%
mutate(HB = as.numeric(HB)) %>%
mutate(
Year = case_when(
Year=="12" ~ "2012",
Year=="14" ~ "2014",
Year=="19" ~ "2019")
)
}
slopegraph_by_sex <- function(health, HB, SEX){ Subsetdata <- subset(health, SEX == SEX)
newggslopegraph(Subsetdata , Year , HB, NAME,
Title = "Haemoglobin",
SubTitle = SEX,
Caption = NULL,
RemoveMissing = FALSE)
}
df_healthmeas <- slopegraph_prep(health, "HB")
df_healthmeas_female <- slopegraph_by_sex(df_healthmeas, "Haemoglobin", "female")
df_healthmeas_male <- slopegraph_by_sex(df_healthmeas, "Haemoglobin", "male")
我真正想做的是能够运行这个例子,让它运行,但我觉得我需要让我的变量更通用?
df_healthmeas <- slopegraph_prep(health, "WAZ")
df_healthmeas_female <- slopegraph_by_sex(df_healthmeas, "Weight to Age WAZ", "female")
df_healthmeas_male <- slopegraph_by_sex(df_healthmeas, "Weight to Age WAZ", "male")
任何帮助都将是巨大的感激。
嘿,你的代码已经可以做到了,你只需要指定函数参数。
df_healthmeas <- slopegraph_prep(health_longer = health, HB =WAZ)
你在函数代码中指定的变量只是一个 "虚 "字 所以你可以把它重新写成这样,以提高可读性。
slopegraph_prep <- function(data, var){data %>%
select(NAME:SEX, starts_with("var")) %>%
pivot_longer(cols = starts_with("var"),
names_to = "Year",
names_prefix = "var",
values_to = "var") %>%
mutate(
var = case_when(
var < 0 ~ "NA",
TRUE ~ as.character(var)
)
) %>%
na_if("NA") %>%
mutate(var = as.numeric(var)) %>%
mutate(
Year = case_when(
Year=="12" ~ "2012",
Year=="14" ~ "2014",
Year=="19" ~ "2019")
)
}