I have 4 data frames of climate data. They are formatted such that column 1 is the year, and columns 2:13 are the months and its average of the climate variable of interest.
What I want (to input into another function that needs this format) is a df where column 1 is year, column 2 is month, column 3 is the corresponding climate data from df1, column 4 is the the corresponding climate data from df2 etc.
so I have is
Year | Jan | Feb |
---|---|---|
1991 | 33.3 | 30.1 |
1992 | 32.1. | 29.7 |
x 4
and what I want is
Year. | Month | Tmax | Tmin |
---|---|---|---|
1991 | Jan | 33.3 | 22.1 |
1991 | Feb | 30.1 | 20.1 |
This is different from this question because I wish to reshape and combine multiple data frames. It is probably valuable because this format of climate data is common, and we commonly want combine multiple climate variables into one table, as I am trying to do, so the specifics of combining is relevant.
I can do it using the following for loop and remaking the data frame as below, but I am trying to wean myself off for loops as I work with larger datasets. What is a more efficient way to reshape this data?
rainvec <- c()
for (i in 42:nrow(rain)) {
for (j in 2:13) {
rainvec <- c(rainvec, rain[[i,j]])
}
}
tminvec <- c()
for (i in 1:nrow(tmin)) {
for (j in 2:13) {
tminvec <- c(tminvec, tmin[[i,j]])
}
}
tmaxvec <- c()
for (i in 1:nrow(tmax)) {
for (j in 2:13) {
tmaxvec <- c(tmaxvec, tmax[[i,j]])
}
}
tmeanvec <- c()
for (i in 1:nrow(tmean)) {
for (j in 2:13) {
tmeanvec <- c(tmeanvec, tmean[[i,j]])
}
}
years <- sort(rep(tmean[[1]], 12))
months <- rep(1:12, nrow(tmin))
clim <- data.frame(years, months, rainvec, tminvec, tmaxvec, tmeanvec)