stack_df {lazy.tools}R Documentation

Vertically Stack Data Frames / Matrices with Different Sets of Variables

Description

Vertically Stack Data Frames / Matrices with Different Sets of Variables

Usage

stack_df(..., sort = 0)

Arguments

...

data frames or matrices

sort

= 1 to alphabetically sort the columns of the result
Otherwise, the order of the original data frames will be kept.

Details

Conceptually, stack_df( df1, df2 ) is equivalent to

 t( merge( cbind(t(df1),cn=colnames(df1)), cbind(t(df2),cn=colnames(df2))
         , by="cn", all=1 ) )

.

Using the data frames in the example section, the core part is:

res <- merge( data.frame(df1m,id=1:nrow(df1m))
            , data.frame(df2m,id=(1:nrow(df2m))+nrow(df1m)), all=1 )
 

which vertically stacks data frames because the values of the common variable id are unique.
Note that, since check.names=0 and optional=1 are used when creating data frames, the resulting data frame may not have valid column names.

When all the row names are unique, it will be used as the row names of the resulting data frame. Otherwise, native make.unique will be used to mark the duplicate row names which appends ".n" to the original names.

Value

A data frame or a matrix

Examples

A <- demomat(5,4,3,cnroot="")
A1 <- A[,,1]; A2 <- A[,,2]; A3 <- A[1:2,,3]
colnames(A1) <- sub("4","v4",colnames(A1))
colnames(A2) <- sub("4","v4",colnames(A2))
colnames(A3) <- sub("4","v4",colnames(A3))
rownames(A1) <- paste("a1_",1:nrow(A1),sep="")
rownames(A2) <- paste("a2_",1:nrow(A2),sep="")
rownames(A3) <- paste("a3_",1:nrow(A3),sep="")
rownames(A3)[2] <- "a1_2"
A1m <- A1[,c(1,4)]; A2m <- A2[,c(1,3), drop=0]; A3m <- A3[,c(4,2,3)]
rownames(A2m) <- NULL

print(A1m)
print(A2m)
print(A3m)

res <- stack_df( A1m, A2m, A3m )
Print(res)

# no factors allowed.
df1m <- as.data.frame(A1m, stringsAsFactors=0)
df2m <- as.data.frame(A2m, stringsAsFactors=0)
df2m[,2] <- paste("c",df2m[,2],sep="")
df3m <- as.data.frame(A3m, stringsAsFactors=0)

res <- stack_df( df1m, df2m, df3m )
Print(df1m, df2m, df3m)
Print(res)
res2 <- stack_df( df2m, df3m, df1m )
Print(res2)
res3 <- stack_df( df1m, df2m, df3m, sort=1 )
Print(res3)

# use of native Reduce function
res0 <- Reduce( stack_df, list(df1m, df2m, df3m) )

res4 <- stack_df( A=demomat(3,2), b=letters[1:3] )
Print(res4)



[Package lazy.tools version 0.1.6 ]