[R] Extending data frame with longer columns

Paul Hiemstra p.hiemstra at geo.uu.nl
Wed Feb 17 13:45:55 CET 2010

Ralf B wrote:
> Hi,
> I am a beginner in R and have only read a few chapters in the R book,
> I was not able to find a solution for this simple problem.
> I have an empty data frame:
> a=data.frame(name="test")
> which I would like to extend in a for-loop (with data extracted from a
> database). Ideally I would like to extend the data frame like this:
> a["new_1"] = 1:10
> a["new_1"] = 1:12
> a["new_1"] = 1:14
I would first read all the data into a list (maybe using lapply), where 
the columns are the parts of the list. Then you can find out which one 
is longest, and add NA's at the end of the other columns, and than use 
do.call("cbind", list_of_columns) to get the resulting data.frame:

note that I use apply type of constructs a lot, it is sort of one line 
for loop.

# Create a mockup list for this particular example
column_list = lapply(round(runif(5, 1, 10)), function(len_column) {
    rep(len_column, times = len_column)

# Find the length of the columns in the list
len_columns = sapply(column_list, length)
# add the NA's
dum = lapply(column_list, function(col) {
       c(col, rep(NA, max(len_columns) - length(col)))
# Make the dataframe
dat = data.frame(do.call("cbind", dum))

it is quite a manual way of doing it, maybe someone else knows of an 
available R function to do it. But this is how I would do it.

> R now obviously complains about the changing length of the new
> columns. However, I would like to have missing values being added
> whenever columns are shorter than a newer (longer) column. How can I
> do that?
> Thanks,
> Ralf
> ______________________________________________
> 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.

Drs. Paul Hiemstra
Department of Physical Geography
Faculty of Geosciences
University of Utrecht
Heidelberglaan 2
P.O. Box 80.115
3508 TC Utrecht
Phone:  +3130 274 3113 Mon-Tue
Phone:  +3130 253 5773 Wed-Fri

More information about the R-help mailing list