用R替换NA值为一组随机生成的数值。

huangapple go评论66阅读模式
英文:

Replace NA value with a bunch of randomly generated values in R

问题

我想筛选我的“Title”列,然后用一些在最小和最大年龄范围内随机生成的值替换“Age”列中的NA值。我尝试了以下命令

titanic_df4 <- titanic_df3 %>%
  filter(titanic_df3$Title=='Mr.') %>%
  mutate(Age = replace_na(Age, runif(1, min=14, max=57)))

但它只用范围内的一个特定值替换了NA值。我应该怎么办?

尝试这个

titanic_df4 <- titanic_df3 %>%
  filter(titanic_df3$Title=='Mr.') %>%
  mutate(Age = replace_na(Age, runif(1, min=14, max=57)))
英文:

I want to filter my Title column and then replace the NA values in Age column with a bunch of randomly generated values(within min and max age range). I tried the following command

titanic_df4 &lt;- titanic_df3 %&gt;% filter(titanic_df3$Title==&#39;Mr.&#39;) %&gt;% mutate(Age = replace_na(Age, runif(1, min=14, max=57)))

but it just replace the na value with one specific value within the range. What should I do?

Tried this

titanic_df4 &lt;- titanic_df3 %&gt;% filter(titanic_df3$Title==&#39;Mr.&#39;) %&gt;% mutate(Age = replace_na(Age, runif(1, min=14, max=57)))

答案1

得分: 1

replace_na 只适用于单个值。从 ?replace_na 帮助页面:

> 如果 data 是一个向量,replace 接受一个单个值。此单个值替代向量中的所有 NA 值。

相反,我们可以生成足够的值用于整个向量,并使用 coalesce() 填充 NA 值,使用这些生成的值。

titanic_df3 %>%
  ## Title not titanic_df3$Title
  filter(Title == 'Mr.') %>%
  mutate(Age = coalesce(Age, runif(n(), min=14, max=57)))
英文:

replace_na only works for single values. From the ?replace_na help page:

> If data is a vector, replace takes a single value. This single value replaces all of the NA values in the vector.

Instead we can generate enough values for the whole vector and use coalesce() to fill in the NA values with those generated values.

titanic_df3 %&gt;%
  ## Title not titanic_df3$Title
  filter(Title == &#39;Mr.&#39;) %&gt;% 
  mutate(Age = coalesce(Age, runif(n(), min=14, max=57)))

</details>



huangapple
  • 本文由 发表于 2023年4月13日 23:28:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76007254.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定