繁体   English   中英

R:用“其他”替换稀有值

[英]R: Replace rare values by "others"

我有以下问题:我有一个包含许多变量的数据框df 一个变量是df$size (非数字)。 现在我想用术语“其他”替换所有观察值少于 20 的尺寸。

sort(table(df$size))

这让我大致了解了要替换的值。 但是如何在我的 df 中替换它们?

df$size[sort(table(df$size))<20]="other"

那行不通。

谢谢!

或者dplyr的选项

library(dplyr)
df %>%
   group_by(grp = size) %>%
   mutate(size = replace(size, n() < 20, "other")) %>%
   ungroup %>%
   select(-grp)

与此一起工作

set.seed(123)
df <- data.frame(size = as.character(sample(1:5, size = 100, replace = TRUE)),
                 stringsAsFactors = FALSE)
tabs <- sort(table(df$size))
tab <- tabs[tabs < 20]

df$size[which(df$size %in% names(tab))] <- "other"

library(data.table)回答:

setDT(df)
cnts <- df[,.N, size]
df <- df[cnts, nomatch= 0L, on= 'size'][, size := ifelse(N < 20, 'other', size)]

类类型table与数据框一起使用有点困难。 这里我们使用cnts将所有内容保存在一个对象类中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM