简体   繁体   中英

R- loop over ddply

I need to get history of each row. If my table is:

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))

I need to get for each tel a kind of trend variable of "intentos": for instace actual value /previous value, but for each row. created1=c(NA, 5/1, 1/5, 4/1) for first tel.

My wanted table is:

    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

I tried to create a function to pass to 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)}

If I run this over a vector, it works. So I tried to pass it to the ddply function:

library(plyr)
ddply(aa, .(tel), mutate, mean_hora=mean(intentos), min_hora=min(intentos), created1=g(intentos))

But I get the following error:

Data frame column 'created1' not supported by rbind.fill

My approach (to pass a function to evaluate each vector) was ok? How can I get the desired result using the function I've created?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM