在R

时间:2019-09-17 14:57:58

标签: r dplyr

我有一个数据框,其中一列是具有三个级别的分类变量“组”:“ A”,“ B”,“未知”,并且还具有NA。

我想获取所有的“未知”和NA,并随机分配一半给“ A”,一半给“ B”。我尝试在 dplyr 中使用mutate()replace()函数,但是想不出如何将它们均等地分配给任一组。

2 个答案:

答案 0 :(得分:0)

类似这样的事情...

replacements = sample ( c ( 'A', 'B' ), number_wanted, replace = TRUE )

...应该可以解决问题

答案 1 :(得分:0)

拥有reproducible example (reprex)会很有用。

data.table软件包提供了一个简洁的解决方案。

library(data.table)

setDT(df) # make your data.frame into a data.table

# filter for rows where your grouping variable is NA or equals "Unknown" then randomly select A or B. .N is a special data.table character representing the number of rows in the selection

df[is.na(group_var) | group_var == "Unknown", group_var := sample(c("A", "B"), .N)]