【发布时间】:2018-06-07 13:04:51
【问题描述】:
我正在寻找:
- 写一个函数或者
- 使用 data.table 或
- 使用 dplyr mutate_cond 或
- 使用呼噜声地图功能
复制此功能:
If year = current
columns(7,8,9) = column(6)
Else
If year = current + 1
columns(8,9,10) = column(7)
Else
If year = current + 2
columns(9,10,11) = column(8)
Else
If year = current + 3
columns(10,11,12) = column9)
End If
End If
End If
End If
到目前为止,我已经能够使用以下不整洁的代码创建一个静态解决方案:
tbl.scholar1<-tbl.scholar1%>%mutate_cond(cohort == currentAY, ay_1819=ay_1718, ay_1920=ay_1718, ay_2021=ay_1718)
tbl.scholar1<-tbl.scholar1%>%mutate_cond(cohort == currentAY+1, ay_1920=ay_1819, ay_2021=ay_1819, ay_2122=ay_1819)
tbl.scholar1<-tbl.scholar1%>%mutate_cond(cohort == currentAY+2, ay_2021=ay_1920, ay_2122=ay_1920, ay_2223=ay_1920)
tbl.scholar1<-tbl.scholar1%>%mutate_cond(cohort == currentAY+3, ay_2122=ay_2021, ay_2223=ay_2021, ay_2324=ay_2021)
经过一番修改后,我编写了一个以当前年份和列名作为输入的函数:
tbl.scholar1<-dup.DF(tbl.scholar1, currentYR, "ay_1718", "ay_2324")
函数代码是这样的
dup.DF <- function(df1, currAY, name1, name2) {
df1%>%mutate_cond(cohort == currAY, UQ(rlang::sym(name2)) := UQ(rlang::sym(name1))) #This works!!!!
}
所以不知何故,我知道有一个更优雅的解决方案,使用 data.table、purrr:map 或 dplyr 将动态变量作为向量或列表接收,这样我就不必重复我的函数 n 次迭代带有 for 循环。
The input looks like this....
SYSDATE ID name cohort fundCode ay_1718 ay_1819 ay_1920 ay_2021 ay_2122 ay_2223 ay_2324 ay_2425
0005-11-20 000000000 "last0, first" 1718 316001 1 0 0 0 0 0 0 0
0005-11-20 000000000 "last0, first" 1718 316001 0 1 0 0 0 0 0 0
0005-11-20 000000000 "last0, first" 1718 316001 0 0 1 0 0 0 0 0
0005-11-20 000000000 "last0, first" 1718 316001 0 0 0 1 0 0 0 0
我的预期输出是……
SYSDATE ID name cohort fundCode ay_1718 ay_1819 ay_1920 ay_2021 ay_2122 ay_2223 ay_2324 ay_2425
0005-11-20 000000000 "last0, first" 1718 316001 1 1 1 1 0 0 0 0
0005-11-20 000000000 "last0, first" 1718 316001 0 1 1 1 1 0 0 0
0005-11-20 000000000 "last0, first" 1718 316001 0 0 1 1 1 1 0 0
0005-11-20 000000000 "last0, first" 1718 316001 0 0 0 1 1 1 1 0
【问题讨论】:
-
请展示一个可重现的小例子和预期的输出
-
输入看起来像这样...
-
我还添加了预期的输出。我目前正在使用 mutate_cond 代码四次来生成输出,但我认为有更好的方法来完成此操作。
-
您的示例数据似乎不包含与您的代码相关的任何内容。您是否错误地标记了列?
标签: r function dplyr data.table