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