在R中:将具有前一行数据的行添加到数据帧 [英] In R: Add rows with data of previous row to data frame

查看:102
本文介绍了在R中:将具有前一行数据的行添加到数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框如下所示:

  id year v1 v2 ... 
A 1990 A 5 ...
A 1993 B 1 ...
A 1995 A 2 ...
A 2000 F 3 ...
B 1977 G 1 ...
B 1983 D 2 ...

年变量的起始和结束值ids之间有所不同。我现在想在现有的数据框中添加行数,这些数据不包含在数据集中。这些新观察值应具有前一年的价值。数据框应该是这样的:

  id year v1 v2 ... 
A 1990 A 5 .. 。
A 1991 A 5 ...
A 1992 A 5 ...
A 1993 B 1 ...
A 1994 B 1 ...
A 1995 A 2 ...
A 1996 A 2 ...
A 1997 A 2 ...
A 1998 A 2 ...
A 1999 A 2 ...
A 2000 F 3 ...
B 1977 G 1 ...
B 1978 G 1 ...
B 1979 G 1 ...
B 1980 G 1 ...
B 1981 G 1 ...
B 1982 G 1 ...
B 1983 D 2 ...
/ pre>

非常感谢您的帮助!

解决方案

with data.table

  library(data.table)
DT< - data.table(
id = c(A,A,A,A,B,B),
年= ,
v1 = c(AB,A,F,G,D),
v2 = c(5,1,2,3,1,2)

setkey(DT,id,year)
ans< - DT [,list(year = seq.int年[1],年[.N])),by = id]
setkey(ans,id,year)
DT [ans,roll = TRUE]

roll rollends有很多有用的选项,请参阅?data.table


I have a dataframe that looks like the following:

 id   year    v1    v2   ...
  A   1990     A     5   ...
  A   1993     B     1   ...
  A   1995     A     2   ...
  A   2000     F     3   ...
  B   1977     G     1   ...
  B   1983     D     2   ...

The starting and end values of the "year" variable differ between the ids. I would like to add rows to the existing dataframe for all years that are not included in the dataset right now. These new observations should have the values of the year before. This is how the dataframe should look like:

 id   year    v1    v2   ...
  A   1990     A     5   ...
  A   1991     A     5   ...
  A   1992     A     5   ...
  A   1993     B     1   ...
  A   1994     B     1   ...
  A   1995     A     2   ...
  A   1996     A     2   ...
  A   1997     A     2   ...
  A   1998     A     2   ...
  A   1999     A     2   ...     
  A   2000     F     3   ...
  B   1977     G     1   ...
  B   1978     G     1   ...
  B   1979     G     1   ...
  B   1980     G     1   ...
  B   1981     G     1   ...
  B   1982     G     1   ...
  B   1983     D     2   ...

Many thanks in advance for your help!

解决方案

With data.table

library(data.table)
DT <- data.table(
  id   = c("A", "A", "A", "A", "B", "B"), 
  year = c(1990, 1993, 1995, 2000, 1977, 1983), 
  v1   = c("A", "B", "A", "F", "G", "D"),
  v2   = c(5, 1, 2, 3, 1, 2)
)
setkey(DT, id, year)
ans <- DT[, list(year =  seq.int(year[1], year[.N])), by = id]
setkey(ans, id, year)
DT[ans, roll = TRUE]

There is a lot of useful options for roll and rollends, see ?data.table

这篇关于在R中:将具有前一行数据的行添加到数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆