数据:
DB <- data.frame(orderItemID = 1:10,
salutation= c("Mr","Mrs","not reported","Mrs","Mrs", "Mrs","Company","Mrs","not reported","Company"),
预期结果:
DB <- data.frame(orderItemID = 1:10,
salutation= c("Mr","Mrs","Mrs","Mrs","Mrs", "Mrs","Company","Mrs","Mrs","Mrs"),
早上好!
这次我需要用数据集中最常用的称呼(在示例中为Mrs)替换“未报告”条目。因为在我的原始数据集中不清楚最常用的称呼是否有必要首先找出最常用的称呼,然后将其重新输入到数据集。
尝试使用ifelse函数,但这不起作用:
DB$salutation = ifelse(DB$salutation == "not reported", max(salutation), as.factor(DB$salutation))
希望你们有一些想法可以轻松解决它:)
答案 0 :(得分:1)
你可以从找到最常见的称呼开始:
most_freq <- names(which.max(table(DB$salutation)))
然后,您可以将此值分配给&#34;未报告&#34;:
的每个案例DB$salutation[DB$salutation == "not reported"] <- most_freq
#> DB
# orderItemID salutation
#1 1 Mr
#2 2 Mrs
#3 3 Mrs
#4 4 Mrs
#5 5 Mrs
#6 6 Mrs
#7 7 Company
#8 8 Mrs
#9 9 Mrs
#10 10 Company