R - Use Rbind on Multiple Variables with Similar Names

R - use rbind on multiple variables with similar names

That is the wrong way to handle related items. Better to use a list or dataframe, but you will probably find out why in due course. For now:

do.matrix <- do.call(rbind, lapply( ls(patt="variable"), get) )

Or:

do.matrix <- do.call(rbind, lapply( paste0("variable", 1:10) , get) )

elegant way to use rbind() on multiple dataframes with similar names?

Always try to rigorously capture relations between related instances of data, or related data and methods, or related methods. This generally helps ease aggregate manipulation such as your rbind requirement.

For your case, you should have defined your related data.frames as a single list from the beginning:

foo <- list(data.frame(...), data.frame(...), ... );

And then your requirement could be satisfied thusly:

do.call(rbind, foo );

If it's too late for that, then the solution involving repeated calls to get(), as described in the article to which you linked, can do the job.

R - rbind multiple dataframes in list based on pattern in dataframe name

We can find out which list have "01" in their names using grepl (vals). We then create a new list, one with all vals index together and the other one without them and assign them names.

vals <- grepl("01", names(list_df))
setNames(list(do.call(rbind, list_df[vals]),
do.call(rbind, list_df[!vals])), new_list)

How to rbind different data frames with different column names?

Simply use:

colnames(E)=colnames(N1)=colnames(N2)

D <- rbind(E, N1, N2)

Remember that for the rbind to work the dataframes should have the same number of columns.

Aggregate multiple variables with rbind

A dplyr approach would be:

df %>%
bind_rows(df %>%
group_by(year) %>%
summarize(county = 'Florida', across(starts_with('value'), sum))) %>%
arrange(year, county)
#> year county value1 value2 value3 value4
#> 1 2005 Alachua County 3 3 3 3
#> 2 2005 Baker County 9 9 9 9
#> 3 2005 Bay County 5 5 5 5
#> 4 2005 Florida 17 17 17 17
#> 5 2006 Alachua County 6 6 6 6
#> 6 2006 Baker County 8 8 8 8
#> 7 2006 Bay County 8 8 8 8
#> 8 2006 Florida 22 22 22 22
#> 9 2007 Alachua County 8 8 8 8
#> 10 2007 Baker County 4 4 4 4
#> 11 2007 Bay County 10 10 10 10
#> 12 2007 Florida 22 22 22 22


Related Topics



Leave a reply



Submit