减去R中的多列

问题描述 投票:0回答:1

我有300列的df,名称分别为N0,N1,N2,N3 ... N300。所有值均为数字(无NA)。我想将N1-N0减去到新列中,我们将其命名为x。然后,我想减去N2-X以获得新列,该列随后将用作N3-last减法。这是一个例子

N0   N1  N2
1     2   3
0     1   2
1     1   0

第一步:N1-N0 = x

X
-
1
1
0

第二步:N2-X = Y

Y
-
2
1
0

依此类推...继续为我的300列这样做!

提前谢谢!

r loops multiple-columns subtraction
1个回答
0
投票

这应该起作用:

nc = ncol(df)
nc_odd = seq(1, nc, by = 2)
nc_even = seq(2, nc, by = 2)
result = rowSums(df[nc_even]) - rowSums(df[nc_odd])
if(nc %% 2 == 1) result = -result # flip sign if there is an odd number of columns
© www.soinside.com 2019 - 2024. All rights reserved.