Reputation: 27
I've got what I know is a really easy question, but I'm stumped and seem to lack the vocabulary to seek out the answer effectively with the search bar.
I have a data frame full of numbers similar to this (though not of the same class)
Dat <- structure(c(9L, 9L, 3L, 3L, 2L, 9L, 10L, 5L, 6L, 2L, 4L, 6L,
10L, 2L, 9L, 0L, 1L, 8L, 9L, 7L, 7L, 4L, 4L, 3L, 4L, 7L, 7L,
1L, 0L, 3L, 6L, 10L, 8L, 3L, 0L, 7L, 7L, 1L, 2L, 8L, 5L, 7L,
7L, 8L, 2L, 1L, 10L, 3L, 0L, 2L, 7L, 0L, 0L, 7L, 9L, 8L, 9L,
0L, 4L, 4L, 5L, 6L, 6L, 2L, 4L, 1L, 6L, 2L, 4L, 7L, 5L, 2L, 7L,
4L, 8L, 3L, 3L, 2L, 5L, 1L, 1L, 3L, 8L, 0L, 1L, 8L, 8L, 1L, 1L,
0L, 4L, 4L, 4L, 5L, 6L, 9L, 5L, 2L, 6L, 3L), .Dim = c(10L, 10L
))
All I want to do is replace all values > 5 with a 1, and all values less than 5 with a 0. I've gotten as far as getting a frame with TRUE and FALSE, but can't seem to figure out how to replace things.
Datlog <- Dat > 5
Any help would be greatly appreciated. Thank you.
Upvotes: 0
Views: 61
Reputation: 193527
If I read your question correctly, you'll kick yourself for the answer:
(Dat > 5) * 1
TRUE
and FALSE
in R equate to 1
and 0
respectively. As such, the more semantically correct way to do this would be something like:
out <- as.numeric(Dat > 5)
dim(out) <- dim(Dat)
The two step approach is required in this second approach because when you use as.numeric
, the dim
s of the original data are lost.
One way to replace with different values would be to use factor
:
out <- factor((Dat > 5), c(TRUE, FALSE), c("YES", "NO"))
dim(out) <- dim(Dat)
Another way would be basic subsetting and substitution:
out <- Dat
out[out > 5] <- 999
out[out <= 5] <- 0
out
Upvotes: 2