【发布时间】:2020-10-08 08:27:08
【问题描述】:
在以下数据中,两个变量的水平均以数字方式编码
dat = read.csv("https://studio.edx.org/c4x/HarvardX/PH525.1x/asset/assoctest.csv")
head(dat)
我将这些代码替换为字符串,以便于阅读和绘图。我可以使用 dplyr mutate 函数成功地做到这一点。
dat_char = mutate(dat, allele=replace(allele, allele==0, "AA/Aa")) %>%
mutate(allele=replace(allele, allele==1, "aa")) %>%
mutate(case=replace(case, case==0, "control")) %>%
mutate(case=replace(case, case==1, "case"))
上面的代码运行良好,但重复且编写繁琐。我确信有一种方法可以同时执行其中一些替换并精简代码,但我不确定如何。例如,我尝试使用向量作为查找和替换值。
dat_char = mutate(dat, allele=replace(allele, allele==c(0,1), c("AA/Aa", "aa"))) %>%
mutate(case=replace(case, case==c(0,1), c("control", "case")))
head(dat_char)
这只会弄得一团糟,但它让我了解我正在努力实现的目标。
【问题讨论】:
-
您尝试使用
dplyr::case_when吗?
标签: r replace data-cleaning dplyr