Recall the type casting functions as.logical(), as.numeric(), and as.character()
ID: 3358285 • Letter: R
Question
Recall the type casting functions as.logical(), as.numeric(), and as.character(), which allow us to coerce (or cast) a vector into one of a different mode.
Consider the following commands:
char<-c("2","2","0")
num<-0:2
charnum<-data.frame(char,num)
as.numeric(char)
2 2 0
as.numeric(charnum$char)
2 2 1
Question: Apply as.numeric() to char and to charnum$char. Explain why there is a difference in the results. (b) Use the type casting functions to correctly coerce charnum$char into a numeric vector.
Explanation / Answer
Difference is occured since class of charnum$char is factor and class of char is character.So,when we convert factor to numeric it returns level.
Correct way to convert factor to numeric is:
as.numeric(as.character(charnum$char))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.