Reputation: 427
I have a dataframe and some of the vectors have NAs. I'd like to write a function that recodes NA to 0. However, I don't wan't to recode all vectors. I'd rather prefer specifying a list of vectors to which I can refer to when calling the function. The vectors should be recoded within the dataframe.
Here is my dataframe:
structure(list(ahvn13_chiff = structure(1:6, .Label = c("a", "b", "c", "d", "e", "f", "g", "h","i"
), class = c("labelled", "factor"), label = c(ahvn13_chiff = "Sozialversicherungsnummer anonymisiert")),
sex = structure(c(1L, 1L, 1L, 1L, 2L, 2L), label = c(sex = "Geschlecht"), class = c("labelled",
"integer")), yearmonthday_dateofbirth = structure(c(11086070400,
13038710400, 11838355200, 13972348800, 13959993600, 10880870400
), label = c(yearMonthDay_dateOfBirth = "Geburtsdatum"), class = c("labelled",
"numeric")), z100 = c(0L, 1331L, NA, NA, 0L, NA), z102 = c(0L,
222004L, 0L, 25004L, 0L, NA), z104 = c(0L, NA, 0L, NA, 0L,
NA), z106 = c(0L, 3604L, 0L, 0L, 0L, NA)), codepage = 65001L, row.names = c(NA,
6L), class = "data.frame")
I managed to write a code that recodes the NAs of some of the vectors:
data[c("z100","z102")][is.na(data[c("z100","z102")])] <- 0
I then tried to convert this code to a function and ended up with these two options:
na.zero <- function(x) {
x[is.na(x)] <- 0
}
na.zero(data[c("z100","z102")])
na.zero <- function(df,var) {
df[var][is.na(df[var])] <- 0
}
na.zero(data, c("z100","z102"))
However, none of them works. What is wrong and how else can I hand over a list of vectors to a function.
Thank you in advance for your Inputs.
Upvotes: 0
Views: 55
Reputation: 496
2 things:
First you are not returning anything from your functions. Add a return(x)
or return(df)
at the end of both functions.
Second, you would also have to assign the data again to their correct place: (Only applies to your second function)
data[c("z100","z102")] <- na.zero(data[c("z100","z102")])
Because R functions dont change an object in place.
Upvotes: 2