R-循环ddply
R- loop over ddply
我需要获取每一行的历史记录。
如果我的 table 是:
aa<-data.frame(tel=c(1,1,1,1,2,2,2,2,3,3), hora=c(1,2,4,4,1,1,3,4,1,2),
intentos=c(1,5,1,4,9,2,7,8,8,1), contactos=c(0,1,0,0,0,1,0,1,0,1))
我需要为每个电话获取一种 "intentos" 的趋势变量:对于实例实际值/先前值,但对于每一行。 created1=c(NA, 5/1, 1/5, 4/1) 第一个电话。
我想要的table是:
tel hora intentos contactos created1
1 1 1 1 0 NA
2 1 2 5 1 5
3 1 4 1 0 0.2
4 1 4 4 0 4
5 2 1 9 0 NA
6 2 1 2 1 0.222222222
7 2 3 7 0 3.5
8 2 4 8 1 1.142857143
9 3 1 8 0 NA
10 3 2 1 1 0.125
我尝试创建一个传递给 ddply 的函数:
g<-function (tbl) {x<-data.frame(tbl)
for (i in 2:length(tbl) ){
print(paste0(i-1))
print(tbl[i-1])
x[i,1]<-
tbl[i]/tbl[i-1] }
return (x)}
如果我 运行 在矢量上这样做,它就可以工作。
所以我试图将它传递给 ddply 函数:
library(plyr)
ddply(aa, .(tel), mutate, mean_hora=mean(intentos), min_hora=min(intentos), created1=g(intentos))
但我收到以下错误:
Data frame column 'created1' not supported by rbind.fill
我的方法(传递一个函数来评估每个向量)可以吗?如何使用我创建的函数获得所需的结果?
library(dplyr)
a1<-group_by(df,tel)
mutate(a1,mycol=intentos/lag(intentos,1))
Source: local data frame [10 x 5]
Groups: tel
tel hora intentos contactos mycol
1 1 1 1 0 NA
2 1 2 5 1 5.0000000
3 1 4 1 0 0.2000000
4 1 4 4 0 4.0000000
5 2 1 9 0 NA
6 2 1 2 1 0.2222222
7 2 3 7 0 3.5000000
8 2 4 8 1 1.1428571
9 3 1 8 0 NA
10 3 2 1 1 0.1250000
#Or, using pipe notation:
df %>%
group_by(tel)%>%
mutate(mycol=intentos/lag(intentos,1))
我需要获取每一行的历史记录。 如果我的 table 是:
aa<-data.frame(tel=c(1,1,1,1,2,2,2,2,3,3), hora=c(1,2,4,4,1,1,3,4,1,2),
intentos=c(1,5,1,4,9,2,7,8,8,1), contactos=c(0,1,0,0,0,1,0,1,0,1))
我需要为每个电话获取一种 "intentos" 的趋势变量:对于实例实际值/先前值,但对于每一行。 created1=c(NA, 5/1, 1/5, 4/1) 第一个电话。
我想要的table是:
tel hora intentos contactos created1
1 1 1 1 0 NA
2 1 2 5 1 5
3 1 4 1 0 0.2
4 1 4 4 0 4
5 2 1 9 0 NA
6 2 1 2 1 0.222222222
7 2 3 7 0 3.5
8 2 4 8 1 1.142857143
9 3 1 8 0 NA
10 3 2 1 1 0.125
我尝试创建一个传递给 ddply 的函数:
g<-function (tbl) {x<-data.frame(tbl)
for (i in 2:length(tbl) ){
print(paste0(i-1))
print(tbl[i-1])
x[i,1]<-
tbl[i]/tbl[i-1] }
return (x)}
如果我 运行 在矢量上这样做,它就可以工作。 所以我试图将它传递给 ddply 函数:
library(plyr)
ddply(aa, .(tel), mutate, mean_hora=mean(intentos), min_hora=min(intentos), created1=g(intentos))
但我收到以下错误:
Data frame column 'created1' not supported by rbind.fill
我的方法(传递一个函数来评估每个向量)可以吗?如何使用我创建的函数获得所需的结果?
library(dplyr)
a1<-group_by(df,tel)
mutate(a1,mycol=intentos/lag(intentos,1))
Source: local data frame [10 x 5]
Groups: tel
tel hora intentos contactos mycol
1 1 1 1 0 NA
2 1 2 5 1 5.0000000
3 1 4 1 0 0.2000000
4 1 4 4 0 4.0000000
5 2 1 9 0 NA
6 2 1 2 1 0.2222222
7 2 3 7 0 3.5000000
8 2 4 8 1 1.1428571
9 3 1 8 0 NA
10 3 2 1 1 0.1250000
#Or, using pipe notation:
df %>%
group_by(tel)%>%
mutate(mycol=intentos/lag(intentos,1))