In R data frames, row names must be unique.
df <- mtcars
rownames(df) <- rep("duplicate!", nrow(df))
> Error in `row.names<-.data.frame`(`*tmp*`, value = value) :
> duplicate 'row.names' are not allowed
> In addition: Warning message:
> non-unique value when setting 'row.names': ‘duplicate!’
Or
df <- data.frame(mtcars, row.names=rep("duplicate!", nrow(mtcars)))
> Error in data.frame(mtcars, row.names = rep("duplicate!", nrow(mtcars))) :
duplicate row.names: duplicate!
What, then, is the motivation for the following behavior with as.data.frame()
? Is this intentional or a bug?
m <- as.matrix(mtcars)
rownames(m) <- rep("duplicate!", nrow(m))
df <- as.data.frame(m)
Resulting in the following:
any(duplicated(rownames(df))) # == TRUE
nrow(df) # == 32
length(unique(rownames(df))) # == 1
df["duplicate!", ] # returns a single row...
> mpg cyl disp hp drat wt qsec vs am gear carb
> duplicate! 21 6 160 110 3.9 2.62 16.46 0 1 4 4
(Run with R version 3.4.3 (2017-11-30))