简体   繁体   中英

Drop rownames/colnames/names without explicitly setting those to NULL in R

Given this data:

data <- read.table(text="
   age married house income gender class
1   22       0     0     28      1     0
2   46       0     1     32      0     0
3   24       1     1     24      1     0
4   23       0     1     40      0     1
5   50       1     1     28      0     1
")

Whenever I take a section of more than one value I also get the row and/or col names, eg:

> data[1, 1:2]
  age married
1  22       0

Is there some way to drop any names and make this nameless (no labels) without explicitly setting anything to NULL beforehand (or loading in a file with row.names=F etc.)?

The goal is just to be certain nothing is attached when something like nameless(..) is called.

# Not OK 
colnames(data) <- NULL
data[1, 1:2]

# OK
nameless(data[1, 1:2])
[1] 22 0

Example:

output
[[1]]
       income                      
     4     36      2      3     NA 

[[2]]
    age             
  1  48   4   5  NA 

Looks a bit silly, but what about:

unname(unlist(data[1, 1:2]))
#[1] 22 0

unlist() has a use.names argument that will drop the names.

unlist(data[1, 1:2], use.names = FALSE)

Or if everything being returned is of the same type you can use eg as.integer() on it:

as.integer(data[1, 1:2])

Borrowing unname from @alexwhan

unname(c(data1[1,1:2]))
[1] 22  0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM