[英]subtracting values from different time steps in R
I am working with some temperature data, and I have to perform a simple subtraction on a data frame where I want to create a new column eg x= df(i)- df(i-1)
, so given the following df.我正在处理一些温度数据,我必须对要创建新列的数据框执行简单的减法,例如
x= df(i)- df(i-1)
,因此给出以下 df.
df<- c(5,10,20,30,40)
I should get the following result:我应该得到以下结果:
(5,10,10,10,40)
I managed to do it with help of other posts on stack overflow using a for loop as follows:我在其他关于堆栈溢出的帖子的帮助下使用 for 循环设法做到了这一点,如下所示:
df<- c(5,10,20,30,40)
x<- array(NA,length(df))
for(i in 2: length(df)){
x[i]<- Mod(df[i-1]-df[i])
}
print(x)
NA 5 10 10 10
I have two problems, first and more important, I need to perform this for a each column of a large data frame that has temperatures at different depths this example is just for a depth=0.5m , so with the for loop takes forever... Is there a more efficient way to do it?我有两个问题,首先,更重要的是,我需要对具有不同深度温度的大型数据框的每一列执行此操作,此示例仅适用于 depth=0.5m ,因此 for 循环需要永远.. . 有没有更有效的方法来做到这一点?
Secondly, I would like that the output would be something like this:其次,我希望输出是这样的:
(5,10,10,10,40)
Many thanks for your help非常感谢您的帮助
Here is base R solution (maybe for your objective)这是基本的 R 解决方案(也许是为了您的目标)
dfout <- rbind(diff(as.matrix(df)),tail(df,1))
Example例子
> df
X1 X2 X3 X4 X5
1 1 2 3 4 5
2 6 7 8 9 10
3 11 12 13 14 15
4 16 17 18 19 20
> dfout
X1 X2 X3 X4 X5
1 5 5 5 5 5
2 5 5 5 5 5
3 5 5 5 5 5
4 16 17 18 19 20
DATA数据
df <- structure(list(X1 = c(1L, 6L, 11L, 16L), X2 = c(2L, 7L, 12L,
17L), X3 = c(3L, 8L, 13L, 18L), X4 = c(4L, 9L, 14L, 19L), X5 = c(5L,
10L, 15L, 20L)), class = "data.frame", row.names = c(NA, -4L))
foo <- function(x) c(diff(x), x[length(x)])
# Examle
df <- c(5,10,20,30,40)
foo(df)
# [1] 5 10 10 10 40
To apply to each column of data.frame, say X, you can do:要应用于 data.frame 的每一列,比如 X,你可以这样做:
X[] <- lapply(X, foo)
# or to assign to a new object
Y <- data.frame(lapply(df, foo))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.