我想通过使用预先创建的项目,用fct_recode重命名因子级别。我首先创建一些标签,并将它们保存到一个列表中:
#Creating the Labels:
LabelsWithN <- c(
sprintf("Man(%s)", FreqGender["Man","Freq"]),
sprintf("Woman(%s)", FreqGender["Woman","Freq"]),
sprintf("Non-Binary(%s)", FreqGender["Non-Binary","Freq"]),
sprintf("Other(%s)", FreqGender["Other","Freq"]),
sprintf("Prefer Not To Disclose(%s)", FreqGender["Prefer not to disclose","Freq"])
)这将创建一个包含“男人(105)”、“女人(51)”等条目的chr列表。现在我想重新标记原始DataSet中的因子(即"Man“--> "Man(105)")来标记图形。我想使用列表项(即LabelsWithN1)或直接使用创建字符串的函数(即sprintf("Man(%s)",FreqGender"Man","Freq")。
然后,我尝试在fct_recode中输入列表项或函数:
#Using the Labels:
DataSet %>%
mutate(`Gender. What_is_your_ge.._` = fct_recode(`Gender. What_is_your_ge.._`, LabelsWithN[1] = "Man", sprintf("Woman(%s)", FreqGender["Woman","Freq"]) = "Woman")) %>%
#THis is just the code for the graph:
ggplot(aes(x = `Gender. What_is_your_ge.._` , y = `Age. How_old_are_you?`, main = "Age Distribution By Gender")) +
geom_boxplot() +
xlab("Gender (n)") +
ylab("Age")但是,这会产生以下结果:
"Unexpected '=' in:
"DataSet %>%
mutate(`Gender. What_is_your_ge.._` = fct_recode(`Gender. What_is_your_ge.._`, LabelsWithN[1] ="无论我使用函数还是列表项,都没有关系。
向量是一个因子,列表中充满了字符。如果我操作代码将因子"man“重命名为"cat”("cat“= "Man"),代码就能正常工作。
如何寻址列表项/在fct_recode中输入函数以使其正常工作?另外,有人能给我解释一下这里的问题是什么吗?如果我打印出LabelsWithN1,我会打印出正确的字符串。
谢谢你和Bw,
1月
发布于 2021-05-20 21:30:44
也许这会有帮助?
x <- factor(c("apple", "bear", "banana", "dear")) # what you want to recode
levels <- c(fruit = "apple", fruit = "banana") # how you want to recode it
x <- fct_recode(x, !!!levels) # recoding ithttps://stackoverflow.com/questions/63398715
复制相似问题