I have this dataframe:
df <- data.frame(group=c("A", "A", "B", "B"), year=c(1980, 1986, 1990, 1992))
group year
1 A 1980
2 A 1986
3 B 1990
4 B 1992
I'd like to modify it in the following way:
This would be the outcome:
group year pre
1 A 1978 pre1980
2 A 1979 pre1980
3 A 1984 pre1986
4 A 1985 pre1986
5 B 1988 pre1990
6 B 1989 pre1990
7 B 1990 pre1992
8 B 1991 pre1992
Adding the new column would be easy..
df$pre <- paste("pre", df$year, sep="")
But I am stuck on how to add the new rows with the respective years (of course creating a whole new data frame would be just as good). Any hints?
base R
ftw:
data.frame(group = rep(df$group, each=2),
year = df[rep(1:nrow(df), each=2),]$year-2:1,
pre = paste0("pre",rep(df$year,each=2)))
# group year pre
# 1 A 1978 pre1980
# 2 A 1979 pre1980
# 3 A 1984 pre1986
# 4 A 1985 pre1986
# 5 B 1988 pre1990
# 6 B 1989 pre1990
# 7 B 1990 pre1992
# 8 B 1991 pre1992
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With