Обновленный ответ - После получения разъяснения ОП по требованию мне пришлось изменить подход.
st_pos <- 6 #concerned column's start position in the given dataframe
df_bkp <- df #data backup
#rename concerned columns as "ay_1718", "ay_1819" etc
names(df)[st_pos:ncol(df)] <- paste("ay", paste0(as.numeric(substr(min(df$year), 1, 2)) + 0:(ncol(df) - st_pos),
as.numeric(substr(min(df$year), 3, 4)) + 0:(ncol(df) - st_pos)),
sep="_")
#copy "year" column's value to the ensuing three columns
cols <- names(df)[st_pos:ncol(df)] #renamed columns
mapply(function(x, y)
df[df$year == x & df$ID == y, which(grepl(x, cols)) + (st_pos-1):(st_pos+2)] <<-
df[df$year == x & df$ID == y, which(grepl(x, cols)) + (st_pos-1)],
df$year, df$ID)
, что дает
> df
SYSDATE ID name year fundCode ay_1718 ay_1819 ay_1920 ay_2021 ay_2122 ay_2223 ay_2324 ay_2425
1 0005-11-20 0 last0, first 1718 316001 700 700 700 700 0 0 0 0
2 0005-11-20 1 last1, first 1819 316002 0 60 60 60 60 0 0 0
3 0005-11-20 2 last2, first 1920 316003 0 0 50 50 50 50 0 0
4 0005-11-20 3 last3, first 2021 316004 0 0 0 400 400 400 400 0
Пример данных: (примечание: я слегка изменил значение Y1, Y2 etc
с 1
на другое значение для иллюстрации)
df <- structure(list(SYSDATE = c("0005-11-20", "0005-11-20", "0005-11-20",
"0005-11-20"), ID = 0:3, name = c("last0, first", "last1, first",
"last2, first", "last3, first"), year = c(1718L, 1819L, 1920L,
2021L), fundCode = 316001:316004, Y1 = c(700L, 0L, 0L, 0L), Y2 = c(0L,
60L, 0L, 0L), Y3 = c(0L, 0L, 50L, 0L), Y4 = c(0L, 0L, 0L, 400L
), Y5 = c(0L, 0L, 0L, 0L), Y6 = c(0L, 0L, 0L, 0L), Y7 = c(0L,
0L, 0L, 0L), Y8 = c(0L, 0L, 0L, 0L)), .Names = c("SYSDATE", "ID",
"name", "year", "fundCode", "Y1", "Y2", "Y3", "Y4", "Y5", "Y6",
"Y7", "Y8"), class = "data.frame", row.names = c(NA, -4L))
# SYSDATE ID name year fundCode Y1 Y2 Y3 Y4 Y5 Y6 Y7 Y8
#1 0005-11-20 0 last0, first 1718 316001 700 0 0 0 0 0 0 0
#2 0005-11-20 1 last1, first 1819 316002 0 60 0 0 0 0 0 0
#3 0005-11-20 2 last2, first 1920 316003 0 0 50 0 0 0 0 0
#4 0005-11-20 3 last3, first 2021 316004 0 0 0 400 0 0 0 0