coding_heart
coding_heart

Reputation: 1295

How to change values in data frame by column class in R

I've got a frame with a set of different variables - integers, factors, logicals - and I would like to recode all of the "NAs" as a numeric across the whole dataset while preserving the underlying variable class. For example:

frame <- data.frame("x" = rnorm(10), "y" = rep("A", 10))
frame[6,] <- NA

dat <- as.data.frame(apply(frame,2, function(x) ifelse(is.na(x)== TRUE, -9, x) ))
dat
str(dat)

However, here the integers turn into factors; when I include as.numeric(x) in the apply() function, this introduces errors. Thanks for any and all thoughts on how to deal with this.

Upvotes: 0

Views: 177

Answers (1)

lukeA
lukeA

Reputation: 54237

apply returns a matrix of type character. as.data.frame turns this into factors by default. Instead, you could do

dat <- as.data.frame(lapply(frame, function(x) ifelse(is.na(x), -9, x) ) )

Upvotes: 1

Related Questions