Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在不同行之间的数据帧中使用apply r_R_Apply - Fatal编程技术网

在不同行之间的数据帧中使用apply r

在不同行之间的数据帧中使用apply r,r,apply,R,Apply,我有一个df a=1:10000 b=1:10000 a=data.frame(a,b) > head(a) a b 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 我想创建一个新的列,它的函数基于a[n]和b[n-1]的值的比较,我想知道我是否可以使用apply函数而不是for循环 d=0 for(i in 1:dim(a)[1]){d=c(d,a[i,1]-a[i-1,2])} 然后我想将最后一列绑定到原始df a=data.frame(a,d) >

我有一个df

a=1:10000
b=1:10000
a=data.frame(a,b)
> head(a)
  a b
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
我想创建一个新的列,它的函数基于a[n]和b[n-1]的值的比较,我想知道我是否可以使用apply函数而不是for循环

d=0
for(i in 1:dim(a)[1]){d=c(d,a[i,1]-a[i-1,2])}
然后我想将最后一列绑定到原始df

a=data.frame(a,d)
> head(a)
  a b d
1 1 1 0
2 2 2 1
3 3 3 1
4 4 4 1
5 5 5 1
6 6 6 1

我的真实df是3825966和21列。我反复地说,应用速度更快,但不知道如何写出来,或者如果可能的话,也许你可以使用
dplyr
lag

library(dplyr)
a %>% mutate(lagb=lag(b)) %>% mutate(d = a-lagb) %>% head()
#   a b lagb  d
# 1 1 1   NA NA
# 2 2 2    1  1
# 3 3 3    2  1
# 4 4 4    3  1
# 5 5 5    4  1
# 6 6 6    5  1

也许您可以使用
dplyr
lag

library(dplyr)
a %>% mutate(lagb=lag(b)) %>% mutate(d = a-lagb) %>% head()
#   a b lagb  d
# 1 1 1   NA NA
# 2 2 2    1  1
# 3 3 3    2  1
# 4 4 4    3  1
# 5 5 5    4  1
# 6 6 6    5  1
你可以做:

a$d <- c(NA, tail(a$a, -1) - head(a$b, -1))
a$d您可以执行以下操作:

a$d <- c(NA, tail(a$a, -1) - head(a$b, -1))

a$d@jogo解决方案非常有效

我这边的一些基准测试结果: 慢跑风格

> a=1:100000
> b=1:100000
> a=data.frame(a,b)
> t=Sys.time()
> a$d <- c(NA, tail(a$a, -1) - head(a$b, -1))
> Sys.time()-t
Time difference of 0.02101493 secs
> #time took 0 sec

>@jogo解决方案非常有效

我这边的一些基准测试结果: 慢跑风格

> a=1:100000
> b=1:100000
> a=data.frame(a,b)
> t=Sys.time()
> a$d <- c(NA, tail(a$a, -1) - head(a$b, -1))
> Sys.time()-t
Time difference of 0.02101493 secs
> #time took 0 sec
>

再快一点

a$d <- a$a - c(NA, a$b[-length(a$b)])
a$da=rnorm(1000000,0,5)
>b=r形式(1000000,0,10)
>a=数据帧(a,b)
>t a$d系统时间()-t
时差为0.03000093秒
> 
>t=系统时间()
>a$d系统时间()-t
时差为0.06505489秒
再快一点

a$d <- a$a - c(NA, a$b[-length(a$b)])
a$da=rnorm(1000000,0,5)
>b=r形式(1000000,0,10)
>a=数据帧(a,b)
>t a$d系统时间()-t
时差为0.03000093秒
> 
>t=系统时间()
>a$d系统时间()-t
时差为0.06505489秒

a$d的效果非常好。谢谢jogo<代码>a$d的工作原理令人惊叹。谢谢jogo!