从R中删除具有重复索引值的面板中的行

时间:2014-03-21 13:38:01

标签: r indexing duplicates row panel

这里是一些示例数据:

date <- c("2012-01-01","2012-01-02","2012-01-02","2012-01-04","2012-01-05","2012-01-03","2012-01-05","2012-01-05","2012-01-01","2012-01-01")
company <- c("A","A","A","A","A","B","B","B","C","C")
var1 <- c(-0.01, -0.013, 0.02, 0.032, -0.002, 0.022, 0.012, 0.031, -0.018, -0.034)
var2 <- c(43, 12, 34, 53, 45, 42, 23, 56, 87, 54)

mydf1 <- data.frame(date, company, var1, var2)
mydf1

#          date company   var1 var2
# 1  2012-01-01       A -0.010   43
# 2  2012-01-02       A -0.013   12
# 3  2012-01-02       A  0.020   34
# 4  2012-01-04       A  0.032   53
# 5  2012-01-05       A -0.002   45
# 6  2012-01-03       B  0.022   42
# 7  2012-01-05       B  0.012   23
# 8  2012-01-05       B  0.031   56
# 9  2012-01-01       C -0.018   87
# 10 2012-01-01       C -0.034   54

我想用plm包运行回归,如果有重复项似乎不起作用(我得到此错误:重复的夫妇(time-id)pdim.default中的错误(索引[[1]] ,索引[[2]])) 这就是为什么我想只保留第一行,如果公司有重复的日期。

data.frame应如下所示:

#          date company   var1 var2
# 1  2012-01-01       A -0.010   43
# 2  2012-01-02       A -0.013   12
# 3  2012-01-04       A  0.032   53
# 4  2012-01-05       A -0.002   45
# 5  2012-01-03       B  0.022   42
# 6  2012-01-05       B  0.012   23
# 7  2012-01-01       C -0.018   87

我该怎么做?谢谢!

1 个答案:

答案 0 :(得分:4)

mydf1[!duplicated(mydf1[c("date", "company")]),]
##         date company   var1 var2
## 1 2012-01-01       A -0.010   43
## 2 2012-01-02       A -0.013   12
## 4 2012-01-04       A  0.032   53
## 5 2012-01-05       A -0.002   45
## 6 2012-01-03       B  0.022   42
## 7 2012-01-05       B  0.012   23
## 9 2012-01-01       C -0.018   87