How to Apply functions to specific set of columns in data frame in R to replace NAs

我与影子孤独终老i 提交于 2021-01-27 21:50:55

问题


I have a data set in which I want to replace NAs in different columns differently. Following is the dummy data set and code to replicate it .

test <- data.frame(ID = c(1:5),
               FirstName = c(NA,"Sid",NA,"Harsh","CJ"),
               LastName = c("Snow",NA,"Lapata","Khan",NA),
               BillNum = c(6:10),
               Phone = c(1213,3123,3123,NA,NA),
               Married = c("Yes","Yes",NA,"NO","Yes"),
               ZIP = c(1111,2222,333,444,555),
               Gender = c("M",NA,"F",NA,"M"),
               Address = c("A","B",NA,"C","D"))
> test
  ID FirstName LastName BillNum Phone Married  ZIP Gender Address
1  1      <NA>     Snow       6  1213     Yes 1111      M       A
2  2       Sid     <NA>       7  3123     Yes 2222   <NA>       B
3  3      <NA>   Lapata       8  3123    <NA>  333      F    <NA>
4  4     Harsh     Khan       9    NA      NO  444   <NA>       C
5  5        CJ     <NA>      10    NA     Yes  555      M       D

In some columns I want to indicate if a value was supplied by customer or not without retaining the supplied value as following.

Availability_Indicator <- function(x){
  x <- ifelse(is.na(x),"NotAvialable","Available")
  return(x)
}
test$FirstName <- Availability_Indicator(test$FirstName)
test$LastName <- Availability_Indicator(test$LastName)
test$Phone <- Availability_Indicator(test$Phone)
test$Address <- Availability_Indicator(test$Address)

I get the following Data

> test
ID    FirstName     LastName BillNum        Phone Married  ZIP Gender
 1 NotAvialable    Available       6    Available     Yes 1111      M
 2    Available NotAvialable       7    Available     Yes 2222   <NA> 
 3 NotAvialable    Available       8    Available    <NA>  333      F
 4    Available    Available       9 NotAvialable      NO  444   <NA>
 5    Available NotAvialable      10 NotAvialable     Yes  555      M

Address
Available
Available
NotAvialable
Available
Available

In married and gender variable I dont want to lose the value of column and just replace the NAs as following.

NotAvailable_Indicator <- function(x){
  x[is.na(x)]<-"NotAvailable"
  return(x)
}
test$Married <- NotAvailable_Indicator(test$Married)
test$Gender <- NotAvailable_Indicator(test$Gender)

I get the following data set.

ID    FirstName     LastName BillNum        Phone      Married  ZIP       Gender      Address
 1 NotAvialable    Available       6    Available          Yes 1111            M    Available
 2    Available NotAvialable       7    Available          Yes 2222 NotAvailable    Available
 3 NotAvialable    Available       8    Available NotAvailable  333            F NotAvialable
 4    Available    Available       9 NotAvialable           NO  444 NotAvailable    Available
 5    Available NotAvialable      10 NotAvialable          Yes  555            M    Available

My problem is that I dont want to repeat the function calls for each column separately as I have about 200 columns. I was not able to use apply functions as I had to subset data then apply the functions using lapply and then cbind again to original data which changed the order of columns. Is there any method where I can supply names of column and the function and I get modified columns along with other columns(which were not changed) in return as a data set or the columns are modified inplace without returning anything(like DataFrame.fillna in python which has argument inplace=logical)


回答1:


We can use tidyverse for doing this

library(dplyr)
#specify the columns of interest 
#if there are any patterns, we can use `matches` or `grep`
nm1 <- names(test)[c(2, 3, 5, 9)]
nm2 <- names(test)[c(6, 8)]


#use `mutate_at` by specifying the arguments 'vars' and 'funs'
test %>% 
    mutate_at(vars(one_of(nm1)), funs(Availability_Indicator)) %>%
    mutate_at(vars(one_of(nm2)), funs(NotAvailable_Indicator))
#ID    FirstName     LastName BillNum        Phone      Married  ZIP       Gender      Address
#1  1 NotAvialable    Available       6    Available          Yes 1111            M    Available
#2  2    Available NotAvialable       7    Available          Yes 2222 NotAvailable    Available
#3  3 NotAvialable    Available       8    Available NotAvailable  333            F NotAvialable
#4  4    Available    Available       9 NotAvialable           NO  444 NotAvailable    Available
#5  5    Available NotAvialable      10 NotAvialable          Yes  555            M    Available

A base R option is to loop through the columns using lapply, apply the function and update the dataset columns

test[nm1] <- lapply(test[nm1], Availability_Indicator)
test[nm2] <- lapply(test[nm2], NotAvailable_Indicator)

data

It is easier to change the values of character compared to factor class column. So, using stringsAsFActors=FALSE in the 'data.frame' call, the non-numeric columns would be character class

test <- data.frame(ID = c(1:5),
           FirstName = c(NA,"Sid",NA,"Harsh","CJ"),
           LastName = c("Snow",NA,"Lapata","Khan",NA),
           BillNum = c(6:10),
           Phone = c(1213,3123,3123,NA,NA),
           Married = c("Yes","Yes",NA,"NO","Yes"),
           ZIP = c(1111,2222,333,444,555),
           Gender = c("M",NA,"F",NA,"M"),
           Address = c("A","B",NA,"C","D"), stringsAsFactors=FALSE)


来源:https://stackoverflow.com/questions/43620936/how-to-apply-functions-to-specific-set-of-columns-in-data-frame-in-r-to-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!