[R] cross-product
Marc Schwartz
marc_schwartz at me.com
Thu Dec 17 16:59:04 CET 2009
On Dec 17, 2009, at 9:47 AM, Chuck White wrote:
> Hello -- I am trying to create a dataframe whose rows are the cross
> product of rows in two other dataframes. Here's an example:
>
> A = data.frame(F1=c('1','2','3','2'))
> B = data.frame(F2=c('4','5'))
> C = data.frame()
> for (x in unique(A[,'F1'])) {
> C = rbind(C, cbind(F1=x,B))
> }
>
> How can I achieve this without the for loop? Thanks.
See ?merge
> merge(unique(A), B)
F1 F2
1 1 4
2 2 4
3 3 4
4 1 5
5 2 5
6 3 5
BTW, avoid using 'C' as the name of an object, as C() is a function in
R. R will typically know the difference, but it is a good defensive
programming habit to avoid assigning objects to pre-existing function
names.
HTH,
Marc Schwartz
More information about the R-help
mailing list