将一个变量的值赋值给另一个新变量

Assign value from one variable to another new variable

我的数据在这里:

x <- data.frame("Year" = c(1945,1945,1945,1946,1946,1946, 1947,1947,1947), "Age" = c(1,2,3,1,2,3,1,2,3), "Value" = c(4,5,6,7,8,9,10,11,12))

我想将“year+1 and age +1”的值赋给一个新变量。前任。对于 year =1945 和 age=1 的情况,我想将值 = 8(从 year = 1946,age =2 )分配给新变量。

我理想的结果是这样的: x <- data.frame("Year" = c(1945,1945,1945,1946,1946,1946, 1947,1947,1947), "Age" = c(1,2,3,1,2,3,1,2,3), "Value" = c(4,5,6,7,8,9,10,11,12),"Year1moereandAge1more"= c(8,9,NA, 11, 12, NA, NA, NA,NA))

感谢您帮助初学者。

使用修改后的 self-join:

library(dplyr)
x %>%
  transmute(Year = Year - 1, Age = Age - 1, Year1moereandAge1more = Value) %>%
  right_join(x) %>%
  arrange(Year, Age)
# Joining, by = c("Year", "Age")
#   Year Age Year1moereandAge1more Value
# 1 1945   1                     8     4
# 2 1945   2                     9     5
# 3 1945   3                    NA     6
# 4 1946   1                    11     7
# 5 1946   2                    12     8
# 6 1946   3                    NA     9
# 7 1947   1                    NA    10
# 8 1947   2                    NA    11
# 9 1947   3                    NA    12