How do I name the “row names” column in r

前端 未结 2 404
既然无缘
既然无缘 2020-11-28 23:48

I\'m working with a data frame in r where my row names are meaningful. Hence, I would like to give the column of row names a name. How do I do this?

2条回答
  •  伪装坚强ぢ
    2020-11-29 00:04

    It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

    # add the rownames as a proper column
    myDF <- cbind(Row.Names = rownames(myDF), myDF)
    myDF
    
    #           Row.Names id val vr2
    # row_one     row_one  A   1  23
    # row_two     row_two  A   2  24
    # row_three row_three  B   3  25
    # row_four   row_four  C   4  26
    

    If you want to then remove the original rownames:

    rownames(myDF) <- NULL
    myDF
    #   Row.Names id val vr2
    # 1   row_one  A   1  23
    # 2   row_two  A   2  24
    # 3 row_three  B   3  25
    # 4  row_four  C   4  26
    


    Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

    myMat <- as.matrix(myDF)
    names(dimnames(myMat)) <- c("Names.of.Rows", "")
    myMat
    
    # Names.of.Rows id  val vr2 
    #   row_one   "A" "1" "23"
    #   row_two   "A" "2" "24"
    #   row_three "B" "3" "25"
    #   row_four  "C" "4" "26"
    

提交回复
热议问题