Home > database >  copy over rows a specific number of times based on column value in R
copy over rows a specific number of times based on column value in R

Time:07-12

Hey guys I have a data frame in R which looks something like the following

FirstName MiddleName LastName
Jim J Jon
Amy K White
Ravi M Khanna

I want to add a column for year and repeat the rows with the number of years, something like

FirstName MiddleName LastName Year
Jim J Jon 2020
Jim J Jon 2021
Jim J Jon 2022
Amy K White 2020
Amy K White 2021
Amy K White 2022
Ravi M Khanna 2020
Ravi M Khanna 2021
Ravi M Khanna 2022

Does anyone have any advice on how I can go about doing this in R? Thanks in advance!

CodePudding user response:

library(tidyverse)

df %>%
  mutate(Year = list(2020:2022)) %>%
  unnest(Year)

# A tibble: 9 x 4
  FirstName MiddleName LastName  Year
  <chr>     <chr>      <chr>    <int>
1 Jim       J          Jon       2020
2 Jim       J          Jon       2021
3 Jim       J          Jon       2022
4 Amy       K          White     2020
5 Amy       K          White     2021
6 Amy       K          White     2022
7 Ravi      M          Khanna    2020
8 Ravi      M          Khanna    2021
9 Ravi      M          Khanna    2022

CodePudding user response:

Using base R

lapply(df , \(x) rep(x , rep(3,3))) |> data.frame() |>
(\(x) `[[<-`(x ,"Year", value = 2020:2022))()
  • output
  FirstName MiddleName LastName Year
1       Jim          J      Jon 2020
2       Jim          J      Jon 2021
3       Jim          J      Jon 2022
4       Amy          K    White 2020
5       Amy          K    White 2021
6       Amy          K    White 2022
7      Ravi          M   Khanna 2020
8      Ravi          M   Khanna 2021
9      Ravi          M   Khanna 2022
  • data
df <- structure(list(FirstName = c("Jim", "Amy", "Ravi"), MiddleName = c("J", 
"K", "M"), LastName = c("Jon", "White", "Khanna")), class = "data.frame", row.names = c(NA, 
-3L))
  •  Tags:  
  • r
  • Related