General Question on conversion between SQL and R
I am starting with this sample dataset:
start = structure(list(id = c(111L, 111L, 111L, 111L, 222L, 222L, 222L
), year = c(2010L, 2011L, 2012L, 2013L, 2018L, 2019L, 2020L),
col2 = c("A", "BB", "A", "C", "D", "EE", "F"), col3 = c(242L,
213L, 233L, 455L, 11L, 444L, 123L), col4 = c(1213L, 5959L,
9988L, 4242L, 333L, 1232L, 98L)), class = "data.frame", row.names = c(NA,
-7L))
This is what I want to do in R:
library(dplyr)
end <- start %>%
mutate(year_end = lead(year),
col2_end = lead(col2),
col3_end = lead(col3),
col4_end = lead(col4)) %>%
mutate_at(vars(ends_with("_end")), ~ifelse(is.na(.), "END", .)) %>%
rename(year_start = year,
col2_start = col2,
col3_start = col3,
col4_start = col4)
Now I try using SQL:
# my attempt to solve the problem
CREATE TABLE end AS
SELECT
id,
year AS year_start,
LEAD(year) OVER (PARTITION BY id ORDER BY year) AS year_end,
col2 AS col2_start,
LEAD(col2) OVER (PARTITION BY id ORDER BY year) AS col2_end,
col3 AS col3_start,
LEAD(col3) OVER (PARTITION BY id ORDER BY year) AS col3_end,
col4 AS col4_start,
LEAD(col4) OVER (PARTITION BY id ORDER BY year) AS col4_end
FROM start;
Is this code doing the same thing as the R?
In the past, I have normally done this kind of in R, but I have my data on an SQL Server and am trying to optimize this code for larger datasets.
I think the code is correct, but I wanted to have a second set of eyes inspect this code for any possible problems. Anyone see any issues?