Hi,

Does anyone why the following code produces different results?

a <- cbind(1:10,1:10)
b <- a
colnames(a) <- c("a","b")

colnames(b) <- c("c","d")


colnames(cbind(a,b))
> [1] "a" "b" "c" "d"

colnames(cbind(ts(a),ts(b)))
> [1] "ts(a).a" "ts(a).b" "ts(b).c" "ts(b).d"

Is this or compatibility reasons? Cbind for xts and zoo does not have this 
feature. I checked the code for stats:::.cbind.ts and the offending piece of 
code is the following:

        ns <- sum(nsers)
        x <- matrix(, n, ns)
        cs <- c(0, cumsum(nsers))
        nm <- character(ns)
        for (i in 1L:nser) if (nsers[i] > 1) {
            cn <- colnames(sers[[i]])
            if (is.null(cn)) 
                cn <- 1L:nsers[i]
            nm[(1 + cs[i]):cs[i + 1]] <- paste(nmsers[i], cn, 
                sep = ".")
        }
        else nm[cs[i + 1]] <- nmsers[i]

Where nsers is the output of .makeNamesTs and nm is the names of the final 
cbinded object. There is quite an effort to make the names of cbinded ts object 
different from the result of cbinded matrix, or data.frame where the resulting 
name is simply concatenated vector of colnames of objects which are cbinded. I 
am interested to know why is that? In my experience, there is always a good 
reason for they way R behaves precisely it does, so in this case maybe I'm 
missing something. For my current needs I'm using the following function:

cbts <- function(...) {
    dots <- list(...)
    cnames <- unlist(lapply(dots,function(l){
        if(is.null(dim(l)))""
        else colnames(l)
        
    }))
    out <- do.call("cbind",dots)
    colnames(out) <- cnames
    out
}

I need this behaviour because I routinely pass ts objects to dynlm, or operate 
on ts objects based on their names, so anything that changes the original name 
is an inconvenience I need to work around.


I've already asked this question on stackoverflow, but did not get answers I 
needed: 
http://stackoverflow.com/questions/18488816/why-cbind-for-ts-objects-behaves-different-from-cbind-for-matrices-and-data-fram

Vaidotas Zemlys

______________________________________________
R-help@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.

Reply via email to