0

我有一个类似于下表的数据集。我想要做的是将每个 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
4

1 回答 1

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
于 2012-11-28T14:34:23.210 回答