簡體   English   中英

將NA和/或因子水平隨機更改為R中的其他因子水平

[英]Randomly changing NAs and/or factor level to other factor levels in R

我有一個數據框,其中一列是具有3個級別的類別變量“組”:“ A”,“ B”,“未知”,並且它還具有NA。

我想獲取所有“未知”和NA,並隨機將一半分配給“ A”,將一半分配給“ B”。 我試過在dplyr中使用mutate()replace()函數,但是想不出如何將它們均等地分配給任一組。

像這樣的東西...

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

...應該可以

有一個可重現的示例(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)]



暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM