I am having trouble converting a table of NAs and different values to 0 for NAs and 1s for the all the values.
Table looks like this:
x y z
NA 8 NA
2 NA NA
9 9 8
...
I was able to convert the NAs to 0 using:
data[is.na(data)] <- 0
But I couldn't manage to convert the other values for all the columns at once.
You can do this with a simple ifelse
(one-liner):
data <- data.frame(ifelse(is.na(data),0,1))
Or even easier:
+!is.na(data)
Both will give you:
## x y z
## 1 0 1 0
## 2 1 0 0
## 3 1 1 1
Data:
data <- structure(list(x = c(NA, 2L, 9L), y = c(8L, NA, 9L), z = c(NA,
NA, 8L)), .Names = c("x", "y", "z"), row.names = c(NA, 3L), class = "data.frame")
Following the same approach as you mentioned in your example:
# example data
df = data.frame(x = c(5,4,NA),
y = c(NA,3,9))
df
# x y
# 1 5 NA
# 2 4 3
# 3 NA 9
df[!is.na(df)] = 1
df[is.na(df)] = 0
# x y
# 1 1 0
# 2 1 1
# 3 0 1
First replace all non NA values with 1 and then (the remaining) NAs with 0. If you replace NAs first, then all your values will be non NA and you'll end up with a dataframe full of 1s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With