如何保存两行之间的差异,同时将其保存在 R 中的相同 data.frame 中?
How to save the difference between the two rows while saving it in the same data.frame in R?
我想计算 Variable X
的每一行的差异,并将其作为单独的 Variable Diff
保存在同一个 data.frame
中。我知道它会给我尺寸错误 - 我希望 Diff
的第一行留在 blank
并且 Diff
blank
行下方的其余值 Diff
library(tidyverse)
set.seed(1500)
DF <- data.frame(A = runif(10,5,20), X = runif(10,100,200))
DF$Diff <- diff(DF$X)
diff
returns 比原始向量或列少 1 的长度。因此,我们需要在开头或结尾附加一个值。使用 NA
而不是 ""
可能更好,因为 ""
是一个字符串,它会将整个向量或列转换为字符 class 因为有一个优先级character
超过 numeric
和 vector
可以容纳一个 class
DF$Diff <- c(NA, diff(DF$X))
DF
# A X Diff
#1 14.359319 120.6950 NA
#2 19.583288 189.0378 68.342790
#3 14.900511 151.1096 -37.928137
#4 10.134497 142.9174 -8.192231
#5 9.658943 121.5167 -21.400654
#6 8.878611 105.0224 -16.494314
#7 10.945591 170.9850 65.962624
#8 19.444123 167.2761 -3.708932
#9 19.240343 172.9342 5.658118
#10 17.199167 151.3785 -21.555779
我想计算 Variable X
的每一行的差异,并将其作为单独的 Variable Diff
保存在同一个 data.frame
中。我知道它会给我尺寸错误 - 我希望 Diff
的第一行留在 blank
并且 Diff
blank
行下方的其余值 Diff
library(tidyverse)
set.seed(1500)
DF <- data.frame(A = runif(10,5,20), X = runif(10,100,200))
DF$Diff <- diff(DF$X)
diff
returns 比原始向量或列少 1 的长度。因此,我们需要在开头或结尾附加一个值。使用 NA
而不是 ""
可能更好,因为 ""
是一个字符串,它会将整个向量或列转换为字符 class 因为有一个优先级character
超过 numeric
和 vector
可以容纳一个 class
DF$Diff <- c(NA, diff(DF$X))
DF
# A X Diff
#1 14.359319 120.6950 NA
#2 19.583288 189.0378 68.342790
#3 14.900511 151.1096 -37.928137
#4 10.134497 142.9174 -8.192231
#5 9.658943 121.5167 -21.400654
#6 8.878611 105.0224 -16.494314
#7 10.945591 170.9850 65.962624
#8 19.444123 167.2761 -3.708932
#9 19.240343 172.9342 5.658118
#10 17.199167 151.3785 -21.555779