I merged two datasets and am trying to convert a character variable into a numeric variable using as.numeric
. My merged dataset is called “total” and the variable I want to convert is called “d”. The code I used:
na.omit(total)
as.numeric(total$d)
It is still returning the same warning, though, and printing the same output. Not sure what I’m doing wrong?
I also tried using na.omit
on total$d
. In both cases it seemed to work, in that I got no warnings or errors – only the conversion isn’t working.
shh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
Here is an example of why you are having NAs
introduced into your dataset, and how you might choose to handle them:
df <- data.frame(
items = letters[1:5],
qty = c("5","7","6b","2","p")
)
# attempt to convert values in column into numeric values
df$qty <- as.numeric(df$qty)
print(df)
items qty
1 a 5
2 b 7
3 c NA
4 d 2
5 e NA
# NA handling 1: remove NAs and lose some rows in the dataset
df <- na.omit(df)
print(df)
items qty
1 a 5
2 b 7
4 d 2
# NA handling 2: replace NAs and retain the number of rows in the dataset
df[is.na(df)] <- 0
print(df)
items qty
1 a 5
2 b 7
3 c 0
4 d 2
5 e 0
3