please help
please help

Reputation: 197

Convert column with missing data from character to numeric without NA issues

I have a dataframe with missing data and I want to convert it from character to numeric. In doing so, the missing element is set to NA. How can I set the NA to a blank numeric element (i.e. remove the NA) and keep the column as numeric?

For example:

df <- data.frame(
  ID = c("A", "B", "C", "D"), 
  X1 = c("237.7", "191.8", "95.4", "48.1"), 
  X2 = c("234.3", "766.4", "167.6", "")
)
   
str(df)
#> 'data.frame':    4 obs. of  3 variables:
#>  $ ID: chr  "A" "B" "C" "D"
#>  $ X1: chr  "237.7" "191.8" "95.4" "48.1"
#>  $ X2: chr  "234.3" "766.4" "167.6" ""

df[2:3] <-  lapply(df[2:3], as.numeric)

df
#>   ID    X1    X2
#> 1  A 237.7 234.3
#> 2  B 191.8 766.4
#> 3  C  95.4 167.6
#> 4  D  48.1    NA

Upvotes: 0

Views: 1453

Answers (1)

Joon
Joon

Reputation: 91

In short, you cannot have blank numeric data in R. Missing numeric values are required to be NA values in R. Missing character values can be empty strings as you've demonstrated but this means that the other values in the vector or column have to be characters as well. The main point is that vectors in R cannot have mixed classes.

However, if you are exporting this data frame into a file and need NA values to be blank, then try something like this:

write.csv(df, file = "my_df.csv", na = "")

Upvotes: 2

Related Questions