Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

r - Display row names in a data.table object

Reference: While trying to answer this very basic question, I suddenly realized that I wasn't able to display rownames in a data.table object

Toy example

library(data.table)
DT <- data.table(A = letters[1:3])
DT
##    A
## 1: a
## 2: b
## 3: c
row.names(DT) <- 4:6
row.names(DT)
## [1] "4" "5" "6" # seem to work

or

rownames(DT) <- 7:9
rownames(DT)
## [1] "7" "8" "9" # seems to be ok too

But when displaying the data itself, row names remains unchanged

DT
##    A
## 1: a
## 2: b
## 3: c

I would assume data.table ignores unnecessary attributes for efficiency purposes, but attributes seem to disagree

attributes(DT)
# $names
# [1] "A"
# 
# $row.names
# [1] 7 8 9
# 
# $class
# [1] "data.table" "data.frame"
# 
# $.internal.selfref
# <pointer: 0x0000000000200788>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is more or less verbatim from comments.

data.table doesn't support row names. This is intentional, as row names are a bad design choice, because they are far more cumbersome to use than columns (and especially so in data.table, where columns are so much easier to deal with than in data.frame) and are only a subset of what kind of data columns can represent (recall that row names in data.frame are a character vector only, whereas columns can be anything).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...