Home Forums Main Forums R Forum 4 ways to convernt row names in R into an explicit column

  • 4 ways to convernt row names in R into an explicit column

     Justin updated 4 years ago 1 Member · 1 Post
  • Justin

    Administrator
    November 12, 2020 at 10:20 pm
    Up
    0
    Down

    In R programming, sometimes we need to convert row names into an explicit column and then use it. For example, given below score data frame, the student name appears as row names rather than an explicit column, we
    want to add it as a new column to existing data.

    gender age score

    Alice F 24 89
    Peter M 27 73
    Ivy F 32 91

    We have at least 4
    ways to achieve it.

    1. Use the $ attach sign in Base R.

    score$student_name<- rownames(score)

    2. Use the mutate() function in dplyr package

    new<- rownames(score)
    score<- score %>% mutate(student_name= new)

    3. Use the rownames_to_column() function in tibble pakacge.

    library(tibble)
    score <- score %>% rownames_to_column("student_name")

    4. Use the setDT() function in data.table package

    library("data.table")
    setDT(score, keep.rownames="student_name")

    All these 4 ways give the same results, isn’t it cool? However, please note that the student_name was added as a character column rather than a numeric one in each method. You can convert it into numeric by using the as.numeric() function if needed.

    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.
    • This discussion was modified 4 years ago by  Justin.

Log in to reply.

Original Post
0 of 0 posts June 2018
Now