df[,paste0(names(df)[3:4],names(df)[2:3])] <- df[,names(df)[3:4]] - df[,names(df)[2:3]]
df
SerialNo Reading1 Reading2 Reading3 Reading2Reading1 Reading3Reading2
1 1 100 102 107 2 5
2 2 102 105 109 3 4
3 3 119 120 129 1 9
4 4 99 115 118 16 3
5 5 200 207 209 7 2
PS:我假设列按顺序排列为1,2,3等。
,
这是一个整洁的解决方案,它返回格式相似的数据帧。它将数据转换为长格式(output:
(10,10,.....)
),应用pivot_longer
函数,进行减法,然后再扩展回原始格式(lag
)。
pivot_wider
,
我们可以逐行使用apply
来计算连续列之间的差异。
temp <- t(apply(df[-1],1,diff))
df[paste0('ans',seq_len(ncol(temp)))] <- temp
df
# SerialNo Reading1 Reading2 Reading3 ans1 ans2
#1 1 100 102 107 2 5
#2 2 102 105 109 3 4
#3 3 119 120 129 1 9
#4 4 99 115 118 16 3
#5 5 200 207 209 7 2
,
另一种选择是使用简单的for
遍历数据框的列。我认为这种解决方案可能更容易理解,特别是如果您开始使用R。
#Create a data frame with same rows as your df and number of cols-1
resul<-as.data.frame(matrix(nrow=nrow(df),ncol=(ncol(df)-1)))
#Add the SerialNo column to the first column of results df
resul[,1]<-df[,1]
#Set the name of the first column to SerialNo (as the first colname of df)
colnames(resul)[1]<-colnames(df)[1]
#Loop over the Reading columns of df (from the second column to the last minus 1)
for(i in 2:(ncol(df)-1)){
#Do the subtraction
resul[,i] <- df[,i+1]-df[,i]
#Set the colname for each iteration
colnames(resul)[i]<-paste0(colnames(df)[i+1],"-",colnames(df)[i])
}
本文链接:https://www.f2er.com/2915900.html