5
votes

I tried to remove both rownames and colnames of a data.frame. As Jason saied, this can be done with unname then set rownames to NULL. I noticed that the manual says using unname with option force = T would do the same thing in single step:

force logical; if true, the dimnames (names and row names) are removed even from data.frames.

however, this doesn't work for me:

d <- data.frame(a = c(x1 = 1, x2 = 2), b = c(x1 = 'a', x2 = 'b'))
unname(d, force = T)

# Error in `dimnames<-.data.frame`(`*tmp*`, value = NULL) : 
#   invalid 'dimnames' given for data frame

what is the reason?

sessionInfo()
# R version 3.3.1 (2016-06-21)
# Platform: x86_64-pc-linux-gnu (64-bit)
# Running under: Ubuntu 16.04.1 LTS
# 
# locale:
#  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
# [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
# 
# attached base packages:
# [1] stats     graphics  grDevices utils     datasets  methods   base
2

2 Answers

4
votes

Weird. Looks like a bug from here (code behaviour doesn't match documentation).

As a work-around, to remove the rownames, you'll need to:

> d <- unname(d)
> rownames(d) <- NULL
> d

1 1 a
2 2 b

The left-most column of numbers is R's standard data.frame row numbering and is applied to data.frames without rownames.

-1
votes

in case you need a solution for your data but doesn't give answer for why does force = T not working.

#read data
d <- data.frame(a = c(x1 = 1, x2 = 2), b = c(x1 = 'a', x2 = 'b'))

original data

#convert to matrix
m1 <- as.matrix(d) 
#remove dimnames
m2 <- matrix(mm1, ncol = ncol(d), dimnames = NULL)
m2 #output the data

result

Seems that unname() is not working for data.frame even if does say it works in documentation.