Thomas
Thomas

Reputation: 23

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. So if Var1 = NA, then Freq = 0.

See picture

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?

Upvotes: 0

Views: 1984

Answers (1)

Steven
Steven

Reputation: 3294

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

Upvotes: 2

Related Questions