[R] cbind and cbind.data.frame

Michael Weylandt michael.weylandt at gmail.com
Tue Jul 10 05:28:04 CEST 2012


Short answer: there is a default method used here which returns a matrix. It's defined at the C-level for speed so you don't see it with methods()

Longer: cbind() isn't a regular S3 generic since it has no UseMethod(). Look at WRE and R-Internals (internal generics) for more info. 

Best (and good question!),
Michael

On Jul 9, 2012, at 10:21 PM, James Long <jpl2116 at gmail.com> wrote:

> ## Hi, I'm having trouble understanding how the cbind function decides what
> method to apply to its arguments. Easy cut and paste code below.
> 
>> 
> 
>> 
> 
>> 
> 
>> ## create two columns
> 
>> c1 <- c("A","A","B","B")
> 
>> c2 <- 1:4
> 
>> 
> 
>> ## cbind outputs a matrix with elements that are characters, seems
> reasonable
> 
>> out <- cbind(c1,c2)
> 
>> out
> 
>     c1  c2
> 
> [1,] "A" "1"
> 
> [2,] "A" "2"
> 
> [3,] "B" "3"
> 
> [4,] "B" "4"
> 
>> class(out)
> 
> [1] "matrix"
> 
>> mode(out)
> 
> [1] "character"
> 
>> 
> 
>> 
> 
>> ## there are two methods associated with cbind. so i assume that
> 
>> ## cbind is calling the data.frame method, because neither of my
> 
>> ## arguments are of ts class
> 
>> methods(cbind)
> 
> [1] cbind.data.frame cbind.ts*
> 
> 
>   Non-visible functions are asterisked
> 
>> 
> 
>> 
> 
>> ## now i explicitly tell cbind to use the data.frame method
> 
>> ## (which is what i assumed it was doing automatically in the last
> example)
> 
>> ## but this produces something very different from before, a data.frame
> 
>> out2 <- cbind.data.frame(c1,c2)
> 
>> out2
> 
>  c1 c2
> 
> 1  A  1
> 
> 2  A  2
> 
> 3  B  3
> 
> 4  B  4
> 
>> class(out2)
> 
> [1] "data.frame"
> 
>> mode(out2)
> 
> [1] "list"
> 
>> 
> 
>> 
> 
>> ## can someone explain why these outputs are different. Thanks, James.
> 
>> 
> 
> 
> 
> 
> 
> 
> 
> c1 <- c("A","A","B","B")
> 
> c2 <- 1:4
> 
> out <- cbind(c1,c2)
> 
> out
> 
> class(out)
> 
> mode(out)
> 
> methods(cbind)
> 
> out2 <- cbind.data.frame(c1,c2)
> 
> out2
> 
> class(out2)
> 
> mode(out2)
> 
>    [[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at 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.



More information about the R-help mailing list