在下面的数据中,两个变量的水平都是用数字编码的
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)这只会弄得一团糟,但它让我明白了我想要实现的目标。
发布于 2020-06-18 18:01:00
你可以在这里使用简单的ifelse,但是如果你有多个值要替换,你可以考虑recode或case_when:
library(dplyr)
dat %>%
mutate(allele = recode(allele, `0` = 'AA/Aa', `1` = 'aa'),
case = recode(case, `0` = 'control', `1` = 'case'))发布于 2020-06-18 18:05:43
这也可能行得通:
library(dplyr)
dat_char <- mutate(dat,
allele = factor(allele,
levels = c(0, 1),
labels = c("AA/Aa", "aa")),
case = factor(case,
levels = c(0, 1),
labels = c("control", "case")))https://stackoverflow.com/questions/62447298
复制相似问题