Row names & column names in R

后端 未结 4 2181
借酒劲吻你
借酒劲吻你 2020-12-23 19:31

Do the following function pairs generate exactly the same results?

Pair 1) names() & colnames()

Pair 2) rownames()

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 19:54

    And another expansion:

    # create dummy matrix
    set.seed(10)
    m <- matrix(round(runif(25, 1, 5)), 5)
    d <- as.data.frame(m)
    

    If you want to assign new column names you can do following on data.frame:

    # an identical effect can be achieved with colnames()   
    names(d) <- LETTERS[1:5]
    > d
      A B C D E
    1 3 2 4 3 4
    2 2 2 3 1 3
    3 3 2 1 2 4
    4 4 3 3 3 2
    5 1 3 2 4 3
    

    If you, however run previous command on matrix, you'll mess things up:

    names(m) <- LETTERS[1:5]
    > m
         [,1] [,2] [,3] [,4] [,5]
    [1,]    3    2    4    3    4
    [2,]    2    2    3    1    3
    [3,]    3    2    1    2    4
    [4,]    4    3    3    3    2
    [5,]    1    3    2    4    3
    attr(,"names")
     [1] "A" "B" "C" "D" "E" NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA  NA 
    [20] NA  NA  NA  NA  NA  NA 
    

    Since matrix can be regarded as two-dimensional vector, you'll assign names only to first five values (you don't want to do that, do you?). In this case, you should stick with colnames().

    So there...

提交回复
热议问题