How to Convert a Character to Numeric in R | String Vector & Data Frame Column | as.numeric Function
HTML-код
- Опубликовано: 22 авг 2024
- How to converst a character vector to numeric in R in the R programming language. More details: statisticsglob...
R code of this video:
vec <- as.character(c(5, 3, 6, 3, 6, 6, 5)) # Create example vector
vec
class(vec) # Class of example vector
vec_num <- as.numeric(vec) # Apply as.numeric()
vec_num
class(vec_num) # Class of new vector
data <- data.frame(x1 = as.character(c(4, 4, 4, 2, 3, 2)), # Create example data frame
x2 = 6:1,
x3 = as.character(1:6))
data
sapply(data, class) # Classes of columns
data_new1 <- data # Convert one column to numeric
data_new1$x1 <- as.numeric(data_new1$x1)
data_new1
sapply(data_new1, class) # Updated classes
data_new2 <- data # Change all character columns
char_columns <- sapply(data_new2, class) == "character"
data_new2[ , char_columns] <- sapply(data_new2[ , char_columns], as.numeric)
data_new2
sapply(data_new2, class) # Updated classes
Follow me on Social Media:
Facebook - Statistics Globe Page: / statisticsglobecom
Facebook - R Programming Group for Discussions & Questions: / statisticsglobe
Facebook - Python Programming Group for Discussions & Questions: / statisticsglobepython
LinkedIn - Statistics Globe Page: / statisticsglobe
LinkedIn - R Programming Group for Discussions & Questions: / 12555223
LinkedIn - Python Programming Group for Discussions & Questions: / 12673534
Twitter: / joachimschork
Music by bensound.com
Thank you very much, very well explained
That's great to hear. Glad it was helpful!
Muito obrigado pela explicação, consegui realizar os procedimentos, eu tenho muito interesse em aprender a linguagem R.
Hi Adriano, thanks for the positive feedback! Glad the video was helpful to you! Boa sorte aprendendo a linguagem R!