I have开发者_JS百科 a list of data frames, all containing numeric data. How would I go about changing the internal data.frames such that NA values = 0 and anything > or = 1, equals 1. Basically, convert to a data.frames of zero and one.
A quick example.
x <- list()
x$a <- data.frame(c(NA, NA, 7, 7, NA), c(1,1,NA,NA,NA))
x$b <- data.frame(c(NA, NA, 7, 7, NA), c(1,1,NA,NA,NA))
x$c <- data.frame(c(NA, NA, 7, 7, NA), c(1,1,NA,NA,NA))
Generally, if I was only doing one I would do something like:
x$a[x$a >= 1] <- 1
x[is.na(x$a)] <- 0
Now, how do I apply that across an entire list?
UPDATE: Anyone care to add a solution with ldply() for good measure?
There's probably a shorter / more efficient solution, but this works:
lapply(x, function(y) {y[y >= 1] <- 1; y[is.na(y)] <- 0; y})
Nest apply within lapply:
lapply(x, function(x)
apply(x, 2, function(y) ifelse(is.na(y), 0, ifelse(y >= 1, 1, y))
)
)
Here's another really convoluted way to do it. It works by first replacing all NAs by a 0, and then picking the minimum of a number and 1. This is just for the sake of illustration and fun, and is NOT recommended since it is nightmarish code to maintain!
lapply(lapply(x, function(y) replace(y, is.na(y), 0)), sapply, pmin, 1)
精彩评论