You have tried writing:
data <- data %>% if_else(STATUS == "Closed", Address == NA, Address == Address`)
I'll start by just explaining why this didn't work!
- A pipe puts the left hand side into the first argument of the function on the right hand side. if_else() doesn't take a dataframe as an argument.
- Address == NA literally means "is the adress equal to NA", which is, a), not what you want and, b), never appropriate anyway as to detect NA values you'd use is.na().
The correct syntax looks like this:
- We are changing columns, so we use mutate().
- The "Address" column is equal to the if_else() call.
- Our condition is "is the MANAGER column equal to 'closed'?"
- If TRUE, replace with NA_character_ (as it is a character column)
- If FALSE, replace with itself (i.e., don't change it)
I have a dataset with lots of numerical variables, and a character variables that says whether or not low values are suppressed for that observation. In observations where values aren't suppressed, I want to replace NAs 0s (just for specific variables), and I can't figure it out. This is my data:
suppressed var1 var2 none 2 6 none NA 6 none 3 7 none NA NA full 2 6 full 3 6 none 3 NA partial NA 6 none 2 7 none NA NAWhat I want to do is change NA to 0 in Var 1, if Suppressed=none. I tried
and got
Error in if (df$suppressed == "none" & is.na(df$Var1)) 0 else df$Var1 : argument is of length zeroIs there something wrong with my if else statement, or is there another way to do this?
Here's the structure of my data:
structure(list(suppressed = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 2L, 3L, 2L, 2L), .Label = c("full", "none", "partial"), class = "factor"), var1 = c(2, NA, 3, NA, 2, 3, 3, NA, 2, NA), var2 = c(6, 6, 7, NA, 6, 6, NA, 6, 7, NA)), .Names = c("suppressed", "var1", "var2"), row.names = c(NA, -10L), class = "data.frame")How do I replace specific values with NA in R?
Using R replace() function to update 0 with NA
R has a built-in function called replace() that replaces values in a vector with another value, for example, zeros with NAs.
How do I replace specific values in R?
To replace a column value in R use square bracket notation df[] , By using this you can update values on a single column or on all columns. To refer to a single column use df$column_name .
How do you replace values in a vector with Na?
If na is a named vector and as. tag = FALSE , the names indicate variable names, and the associated values indicate those values that should be replaced by NA in the related variable. For instance, set_na(x, na = c(v1 = 4, v2 = 3)) would replace all 4 in v1 with NA and all 3 in v2 with NA .
How do I replace missing values in NA with R?
How to Replace Missing Values(NA) in R: na..
mutate().
Exclude Missing Values (NA).
Impute Missing Values (NA) with the Mean and Median..