MFR MFR - 8 days ago 7
R Question

Is there any way to do operation with data with blank space without converting them to "NA"?

I have the following dataset?

mydata<- data.frame( value = c (1,0,1,"",1,1) )


and I wish to calculate the average of these dataset by ignoring blank space:

mean(mydata$value, na.rm=TRUE)

Answer

As the 'value' column is factor, convert it to character and then to numeric (which automatically converts all non-numeric elements to NA), get the mean by specifying the na.rm argument

mean(as.numeric(as.character(mydata$value)), na.rm = TRUE)