Save the wrong name with indexing

I need to specify data.frame columns with duplicate names. inside data.frame you can use check.names = FALSE to do the mischievous act of the name. But if you specify this, you lose naughty names when indexing. I want to keep these names. So beloe is an example and the result that I get, and I would like to get:

 x <- data.frame(b= 4:6, a =6:8, a =6:8, check.names = FALSE) x[, -1] 

I get:

  a a.1 1 6 6 2 7 7 3 8 8 

I would like to:

  aa 1 6 6 2 7 7 3 8 8 
+4
source share
4 answers

How about this:

 subdf <- function(df, ii) { do.call("data.frame", c(as.list(df)[ii], check.names=FALSE)) } subdf(x, -1) # aa # 1 6 6 # 2 7 7 # 3 8 8 subdf(x, 2:3) # aa # 1 6 6 # 2 7 7 # 3 8 8 
+5
source

Here's an ugly solution

 > tmp <- data.frame(b=4:6, a=6:8, a=6:8, check.names=FALSE) > setNames(tmp[, -1], names(tmp)[-1]) aa 1 6 6 2 7 7 3 8 8 
+3
source

Looking at the code for [.data.frame , it gives this as part of the code

 if (anyDuplicated(cols)) names(y) <- make.unique(cols) 

and I could not see anything in the code that would allow me to skip this check. Looks like we just need to write our own function. It is not very safe, although I'm sure a much better version can be created ...

 dropCols <- function(x, cols){ nm <- colnames(x) x <- x[, -cols] colnames(x) <- nm[-cols] x } x <- data.frame(b= 4:6, a =6:8, a =6:8, check.names = FALSE) #x[, -1] dropCols(x, 1) # aa #1 6 6 #2 7 7 #3 8 8 
+3
source

per dirks tongue in the cheek comment:

 safe.data.frame <- function(dat, index) { colnam <-colnames(dat)[index] dat2 <- dat[, index] colnames(dat2) <- colnam dat2 } safe.data.frame(x, -1) 

I was hoping for something better :)

+2
source

Source: https://habr.com/ru/post/1439474/


All Articles