Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and replace values by NA for all columns in DataFrame

Age <- c(90,56,51,'NULL',67,'NULL',51)
Sex <- c('Male','Female','NULL','male','NULL','Female','Male')
Tenure <- c(2,'NULL',3,4,3,3,4)
df <- data.frame(Age, Sex, Tenure)

In the above example, there are 'NULL' values as character/string formate. I am trying to impute NA in place of 'NULL' values. I was able to it for a single column as df$age[which(df$Age=='NULL)]<-NA' However I don't want to write this for all columns.

How to apply similar logic to all columns so that all the 'NULL' values of df are converted to NAs? I am guessing that apply or custom defined function or for loop will do it.

like image 989
Ashish25 Avatar asked Dec 05 '25 07:12

Ashish25


1 Answers

base R solution

replace(df, df =="NULL", NA)
like image 148
CPak Avatar answered Dec 06 '25 21:12

CPak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!