Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

Efficient dynamic addition of rows in dataframe and dynamic calculation in R

I have the following dataframe (ts1):

                D1 Value N
1 20/11/2014 16:00 0.00 
2 20/11/2014 17:00 0.01  1
3 20/11/2014 19:00 0.05  2
4 20/11/2014 22:00 0.20  3
5 20/11/2014 23:00 0.03  4

I would like to insert rows as the number of of (N-1) the new ts1 and rows will be:

                D1 Value N
1 20/11/2014 16:00 0.00  1
2 20/11/2014 17:00 0.01  1
3 20/11/2014 18:00 0.03  1 <---
4 20/11/2014 19:00 0.05  1
5 20/11/2014 20:00 0.10  1 <---
6 20/11/2014 21:00 0.15  1 <---
7 20/11/2014 22:00 0.20  1
8 20/11/2014 23:00 0.03  1

As can be seen lines 3, 5 and 6 were added because of the gap in time (N > 1) the number in ts1$Value is filled in by dividing the gap of ts1$Value and dividing them by the number of new rows. I would like to add the values as efficient as possible with minimum number of going over the dataframe.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the complete solution: The usage of the last command of linear interpolation solves the issue

> Lines <- "D1,Value
+ 1,20/11/2014 16:00,0.00
+ 2,20/11/2014 17:00,0.01  
+ 3,20/11/2014 19:00,0.05  
+ 4,20/11/2014 22:00,0.20  
+ 5,20/11/2014 23:00,0.03"
> ts1 <- read.csv(text = Lines, as.is = TRUE)
> library(zoo)
> z <- read.zoo(ts1, tz = "", format = "%d/%m/%Y %H:%M")
> 
> z0 <- zoo(, seq(start(z), end(z), "hours"))
> zz <- merge(z, z0)
> interpolated <- na.approx(zz)
> interpolated
2014-11-20 16:00:00 2014-11-20 17:00:00 2014-11-20 18:00:00 2014-11-20 19:00:00 2014-11-20 20:00:00 2014-11-20 21:00:00 
               0.00                0.01                0.03                0.05                0.10                0.15 
2014-11-20 22:00:00 2014-11-20 23:00:00 
               0.20                0.03 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...