MGJ-123
MGJ-123

Reputation: 634

How to split dataframe into multiple dataframes by column index

I'm trying to process the weather data specified below. I thought I was on the right track but the pivot_longer is not being used in the correct manor and is causing partial duplicates.

Can anyone offer any suggestions as to how I can edit my code? I guess one way would be to perform the pivot_longer after splitting the dataframe into several dataframes i.e. first dataframe - jan, year, second dataframe - feb, year.

maxT <- read.table('https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/Tmax/ranked/England_S.txt',  skip = 5, header = TRUE) %>%
  select(c(1:24)) %>%
  pivot_longer(cols = seq(2,24,2) , values_to = "year") %>%
  mutate_at(c(1:12), ~as.numeric(as.character(.))) %>%
  pivot_longer(cols = c(1:12), names_to = "month", values_to = "tmax") %>%
  mutate(month = match(str_to_title(month), month.abb),
         date = as.Date(paste(year, month, 1, sep = "-"), format = "%Y-%m-%d")) %>%
  select(-c("name","year","month")) %>%
  arrange(date)

Upvotes: 1

Views: 289

Answers (2)

akrun
akrun

Reputation: 887951

Here is an option with tidyverse, using map2

library(dplyr)
library(purrr)
list_df <- maxT %>% 
     select(seq(1, ncol(.), by = 2)) %>%
     map2(maxT %>% 
           select(seq(2, ncol(.), by = 2)), bind_cols) %>%
     imap( ~ .x %>% 
              rename(!! .y := `...1`, year = `...2`))

-output

map(list_df, head)
#$jan
# A tibble: 6 x 2
#    jan  year
#  <dbl> <int>
#1   9.9  1916
#2   9.8  2007
#3   9.7  1921
#4   9.7  2008
#5   9.5  1990
#6   9.4  1975

#$feb
# A tibble: 6 x 2
#    feb  year
#  <dbl> <int>
#1  11.2  2019
#2  10.7  1998
#3  10.7  1990
#4  10.3  2002
#5  10.3  1945
#6  10    2020
# ...

data

maxT <- read.table('https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/Tmax/ranked/England_S.txt',  skip = 5, header = TRUE) %>%      
        select(c(1:24)) 

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389325

We can use split.default to split group of 2 columns.

list_df <- split.default(maxT, ceiling(seq_along(maxT)/2))

data

maxT <- read.table('https://www.metoffice.gov.uk/pub/data/weather/uk/climate/datasets/Tmax/ranked/England_S.txt',  skip = 5, header = TRUE) %>%
  select(c(1:24)) 

Upvotes: 0

Related Questions