I have a list of data frames
a <- data.frame(V1=c("Dzienna",4.12,"czas", "2022-01-01 00:00:00", "2022-01-01 01:00:00"),
V2=c(NA,NA,"Moc", 0.13, 1.15)
)
b <- data.frame(V1=c("Dzienna",5.17,"czas", "2022-02-01 00:00:00", "2022-02-01 01:00:00"),
V2=c(NA,NA,"Moc", 0.18, 2.05)
)
L1 <- list(a, b)
L1
I want to get two dataframes that will look like below
Dzienna.prod Data
1 4.12 2022-01-01
2 5.17 2022-02-01
Czas Moc
1 2022-01-01 00:00:00 0.13
2 2022-01-01 01:00:00 1.15
3 2022-02-01 00:00:00 0.18
4 2022-02-01 01:00:00 2.05
I am trying to achieve the goal using lapply and do.call, but so far without success
CodePudding user response:
Assuming that every df has this pattern, you can transform each dataframe in the lists to the format you need. Also, from the tidyverse
tag I assume I can use dplyr functions.
For df1 the only pattern I see is the numeric value originating from row 2, column 1 and the date originating from row 4 column 1
f1 <- function(df) {
data.frame(t(df[c(2, 4), 1])) %>%
mutate(X2 = as.Date(X2)) %>%
rename(Dzienna.prod = X1, Data = X2)
}
df1 <- bind_rows(lapply(L1, f1))
> df1
Dzienna.prod Data
1 4.12 2022-01-01
2 5.17 2022-02-01
For f1
I assume that the column Data
is just the date coming from the datetimes in the dataframes.
The only pattern I recognize for the second dataframe is that it comes from the 4th and 5th row of the dataframes in the list.
f2 <- function(df) {
df[4:nrow(L1[[1]]),] %>% rename(Czas = V1, Moc=V2)
}
df2 <- bind_rows(lapply(L1, f2))
> df2
Czas Moc
1 2022-01-01 00:00:00 0.13
2 2022-01-01 01:00:00 1.15
3 2022-02-01 00:00:00 0.18
4 2022-02-01 01:00:00 2.05