简体   繁体   English

R-根据另一列中的NA值更改一列中的值

[英]R - Change value in one column based on NA value in another column

I am working on a dataset which has information about the education of users. 我正在处理一个有关用户教育信息的数据集。

I want to change a value in the Freq column to "0" based on a NA value in Var1. 我想基于Var1中的NA值将Freq列中的值更改为“ 0”。 So if Var1 = NA, then Freq = 0. 因此,如果Var1 = NA,则频率= 0。

看图片

For the life of me I can not figure it out and need some help. 对于我的一生,我无法弄清楚,需要一些帮助。

Do any of you guys know how to deal with this? 你们中有人知道如何处理吗?

Two solutions: 两种解决方案:

library(dplyr)

#Some data
dat <- 
  data.frame(var1 = sample(c(1:3, rep(NA, 5)), 10, TRUE), 
             var2 = rnorm(10), 
             freq = rnorm(10, 100))

#The "dplyr" way
dat %>%
  mutate(freq = ifelse(is.na(var1), 0, freq))

#subset/replace from AdamO
dat$freq[is.na(dat$var1)] <- 0

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

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