我试图在Excel中做更少的事情,而在R中做更多的事情,但是卡在一个简单的计算上。我有一个数周内具有仪表读数的数据框。我需要计算每周的消费量,即从上一列中减去一列。例如,在下面的示例中,我需要从Reading1
中减去Reading2
,并从Reading2
中减去Reading3
。我的实际数据集包含数百个读数,因此我需要找到一种简便的方法来实现此目的。
SerialNo = c(1,2,3,4,5)
Reading1 = c(100, 102, 119, 99, 200)
Reading2 = c(102, 105, 120, 115, 207)
Reading3 = c(107, 109, 129, 118, 209)
df <- data.frame(SerialNo, Reading1, Reading2, Reading3)
df
SerialNo Reading1 Reading2 Reading3
1 1 100 102 107
2 2 102 105 109
3 3 119 120 129
4 4 99 115 118
5 5 200 207 209
答案 0 :(得分:1)
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等。
答案 1 :(得分:1)
这是一个整洁的解决方案,它返回格式相似的数据帧。它将数据转换为长格式(output:
(10,
10,
10,
10,
10,
10,
10,
10,.....)
),应用pivot_longer
函数,进行减法,然后再扩展回原始格式(lag
)。
pivot_wider
答案 2 :(得分:1)
我们可以逐行使用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
答案 3 :(得分:0)
另一种选择是使用简单的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])
}