p>My data.table solution:sapply(c("a", "b", "c", "d", "e"), function(ll) df[ , paste0(ll, 3) := get(paste0(ll, 1)) + get(paste0(ll, 2))])df[]# a1 a2 b1 b2 c1 c2 d1 d2 e1 e2 a3 b3 c3 d3 e3# 1: 5 2 2 6 4 1 10 7 3 9 7 8 5 17 12# 2: 4 8 7 3 3 7 9 6 9 7 12 10 10 15 16# 3: 10 7 6 10 1 9 4 1 2 4 17 16 10 5 6# 4: 3 4 1 7 6 4 7 4 7 5 7 8 10 11 12# 5: 8 3 4 2 2 2 3 3 4 10 11 6 4 6 14# 6: 6 6 5 1 8 10 1 10 5 3 12 6 18 11 8# 7: 2 10 8 9 5 6 2 5 10 2 12 17 11 7 12# 8: 1 1 10 8 9 5 6 9 6 8 2 18 14 15 14# 9: 9 5 3 5 10 3 5 2 1 6 14 8 13 7 7# 10: 7 9 9 4 7 8 8 8 8 1 16 13 15 16 9或更广泛地说:sapply(c("a", "b", "c", "d", "e"), function(ll) df[ , paste0(ll, 3) := Reduce(`+`, mget(paste0(ll, 1:2)))])如果所有变量都符合以 1 或 2 结尾的模式,则可以尝试:If all of the variables fit the pattern of ending with 1 or 2, you might try:stems = unique(gsub("[0-9]", "", names(df)))然后 sapply(stems,...) 这篇关于如何在不重复代码的情况下变异多个变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-31 06:25