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

Комментарии • 4

  • @VictorOtobo
    @VictorOtobo 3 месяца назад +1

    Thank you very much, very well explained

    • @StatisticsGlobe
      @StatisticsGlobe  3 месяца назад

      That's great to hear. Glad it was helpful!

  • @adriano-rj3733
    @adriano-rj3733 Год назад +1

    Muito obrigado pela explicação, consegui realizar os procedimentos, eu tenho muito interesse em aprender a linguagem R.

    • @matthias.statisticsglobe
      @matthias.statisticsglobe Год назад +1

      Hi Adriano, thanks for the positive feedback! Glad the video was helpful to you! Boa sorte aprendendo a linguagem R!