通过复制R中其他行的内容来填充NA

时间:2012-11-28 13:52:51

标签: r duplicates na

我的数据集类似于下表。我想要做的是将每个ID的NA替换为相应ID中的可用数据,除了我想要预测的结果变量。例如,对于ID 1,我想要从1990年到1991年,1992年,1993年的复制信息。对于ID 2,我应该复制从1992年到1990年,1991年和1993年的信息。该ID代表一个群集,比如村庄。最终我想预测失踪年份的结果。我想在R中这样做。

   ID YeStart Author YEAR   Lat    Long Outome
     1    1990  Goroo 2012 23.45 -16.718     20
     1    1991   <NA>   NA    NA      NA     30
     1    1992   <NA>   NA    NA      NA     NA
     1    1993   <NA>   NA    NA      NA     NA
     2    1990   <NA>   NA    NA      NA      2
     2    1991   <NA>   NA    NA      NA     NA
     2    1992 Berthe 2012 20.45 -16.718     NA
     2    1993   <NA>   NA    NA      NA     NA
     3    1990   <NA>   NA    NA      NA     NA
     3    1991 Berthe 2012 40.45 -16.718     NA
     3    1992   <NA>   NA    NA      NA     NA
     3    1993   <NA>   NA    NA      NA     50

1 个答案:

答案 0 :(得分:1)

我很确定这个问题的答案已经在网站的某个地方了。但您可以使用mergecomplete.cases

这些功能来完成
d <- read.table(text="ID YeStart Author YEAR   Lat    Long Outome
     1    1990  Goroo 2012 23.45 -16.718     20
     1    1991   <NA>   NA    NA      NA     30
     1    1992  Goroo 2012 23.45 -16.718     NA
     1    1993   <NA>   NA    NA      NA     NA
     2    1990   <NA>   NA    NA      NA      2
     2    1991   <NA>   NA    NA      NA     NA
     2    1992 Berthe 2012 20.45 -16.718     NA
     2    1993   <NA>   NA    NA      NA     NA
     3    1990   <NA>   NA    NA      NA     NA
     3    1991 Berthe 2012 40.45 -16.718     NA
     3    1992   <NA>   NA    NA      NA     NA
     3    1993   <NA>   NA    NA      NA     50", header=TRUE)

d1 <- d[c('ID', 'YeStart', 'Outome')]
d2 <- d[! names(d) %in% c('Outome', 'YeStart')]
merge(d1, unique(d2[complete.cases(d2), ]))

#    ID YeStart Outome Author YEAR   Lat    Long
# 1   1    1990     20  Goroo 2012 23.45 -16.718
# 2   1    1991     30  Goroo 2012 23.45 -16.718
# 3   1    1992     NA  Goroo 2012 23.45 -16.718
# 4   1    1993     NA  Goroo 2012 23.45 -16.718
# 5   2    1990      2 Berthe 2012 20.45 -16.718
# 6   2    1991     NA Berthe 2012 20.45 -16.718
# 7   2    1992     NA Berthe 2012 20.45 -16.718
# 8   2    1993     NA Berthe 2012 20.45 -16.718
# 9   3    1990     NA Berthe 2012 40.45 -16.718
# 10  3    1991     NA Berthe 2012 40.45 -16.718
# 11  3    1992     NA Berthe 2012 40.45 -16.718
# 12  3    1993     50 Berthe 2012 40.45 -16.718