patternpythonMinor
Merge together multiple dataframes
Viewed 0 times
dataframestogethermultiplemerge
Problem
I'm working on a script where I want to create one dataframe from a series of files with annual baseball data in them.
I'm relatively new to R and I feel like the way I wrote
I'm relatively new to R and I feel like the way I wrote
get_seasons_range() is probably more like writing C# in R, rather than doing it the idiomatic R way. Is there a cleaner way to do this?read_season <- function(yearID) {
season = read.csv(paste("../retrosheetData/gamelog/GL", yearID, ".TXT", sep=""))
glheaders = read.csv("../retrosheetData/gamelog/game_log_header.csv")
names(season) = names(glheaders)
return(season)
}
read_season_range <- function(year_range) {
seasons = read_season(year_range[1])
for(y in year_range) {
if(y == year_range[1])
next
s = read_season(y)
seasons = rbind(seasons, s)
}
return(seasons)
}
sixties = read_season_range(1960:1969)Solution
The
Using base R functions, your
or to wrap it in a function:
for loop can be replaced with a lapply statement.Using base R functions, your
read_season_range example is equivalent to the following one-liner:sixties <- do.call(rbind, lapply(1960:1969, read_season))or to wrap it in a function:
read_season_range <- function(year_range) {
do.call(rbind, lapply(year_range, read_season))
}Code Snippets
sixties <- do.call(rbind, lapply(1960:1969, read_season))read_season_range <- function(year_range) {
do.call(rbind, lapply(year_range, read_season))
}Context
StackExchange Code Review Q#113374, answer score: 5
Revisions (0)
No revisions yet.