改变R中的数据帧

use*_*499 1 row r dataframe

我有一个数据框,第一列从1到365像这样

c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2...
Run Code Online (Sandbox Code Playgroud)

并且第二列有时间像这样一遍又一遍地重复

c(0,30,130,200,230,300,330,400,430,500,0,30,130,200,230,300,330,400,430,500...
Run Code Online (Sandbox Code Playgroud)

所以对于第一列中的每1个值,我在第二列中有相应的时间,然后当我到达2时,时间重新开始,每个2都有相应的时间,

偶尔我会遇到

c(3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4...

c(0,30,130,200,230,330,400,430,500,0,30,130,200,230,300,330,400,430,500...
Run Code Online (Sandbox Code Playgroud)

这里缺少3个中的一个,缺少相应的300个时间.

如何浏览整个数据框并添加这些缺失值?我需要一种方法让R通过并识别任何缺失的值,然后插入一行并在第一列中放入适当的值1到365以及适当的时间.因此,对于给定的示例,R将在230和330之间添加一行,然后在第一列中放置3,在第二列中放置300.该列的某些部分缺少多个连续值.这里和那里不只是一个人

Mat*_*ler 5

编辑:解决方案,所有10次提前明确指定和代码整理/评论

你需要创建另一个data.frame包含每个可能的行,然后merge用你的data.frame.关键方面是all.x = TRUE在最终合并中强制突出显示数据中的差距.我通过对前20个可能的日/时间组合中的15个进行抽样来模拟间隙your.dat

# create vectors for the days and times
the.days    = 1:365
the.times   = c(0,30,100,130,200,230,330,400,430,500)   # the 10 times to repeat

# create a master data.frame with all the times repeated for each day, taking only the first 20 observations
dat.all = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365))[1:20,]

# mimic your data.frame with some gaps in it (only 15 of 20 observations are present)
your.sample = sample(1:20, 15)
your.dat = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365), x3 = rnorm(365*10))[your.sample,]

# left outer join merge to include ALL of the master set and all of your matching subset, filling blanks with NA
merge(dat.all, your.dat, all.x = TRUE)
Run Code Online (Sandbox Code Playgroud)

以下是合并的输出,显示所有20条可能的记录,其间隙清晰可见NA:

   x1  x2          x3
1   1   0          NA
2   1  30  1.23128294
3   1 100  0.95806838
4   1 130  2.27075361
5   1 200  0.45347199
6   1 230 -1.61945983
7   1 330          NA
8   1 400 -0.98702883
9   1 430          NA
10  1 500  0.09342522
11  2   0  0.44340164
12  2  30  0.61114408
13  2 100  0.94592127
14  2 130  0.48916825
15  2 200  0.48850478
16  2 230          NA
17  2 330  0.52789171
18  2 400 -0.16939587
19  2 430  0.20961745
20  2 500          NA
Run Code Online (Sandbox Code Playgroud)