-1

I have a large data frame and part of it look like this:

   id carbon nitrogen sulfer
1   1     NA       NA     NA
2   1     NA       NA     NA
3   1      5        6     78
4   2     NA       NA     NA
5   2     NA       NA     NA
6   2      8        8     67
7   3     NA       NA     NA
8   3     NA       NA     NA
9   3     NA       NA     NA
10  3      7        9     55

Is there a way I can filled the NA values in columns (example carbon), with one value given common to id. For example if we take id == 1 then for column carbon has value of 5 and need to replace NA with 5. I have nearly 200 columns to filled like this.

Any help to automate this is much appreciated.

4

2 回答 2

2

您还没有真正澄清@flodel 在他的评论中指出的问题。无论如何,鉴于您的示例数据中的模式,即碳氮硫的所有值都丢失了,除了每个 id 中的最后一个值,那么您可以试试这个:

library(zoo)
na.locf(df, na.rm = FALSE, fromLast = TRUE)

#    id carbon nitrogen sulfer
# 1   1      5        6     78
# 2   1      5        6     78
# 3   1      5        6     78
# 4   2      8        8     67
# 5   2      8        8     67
# 6   2      8        8     67
# 7   3      7        9     55
# 8   3      7        9     55
# 9   3      7        9     55
# 10  3      7        9     55
于 2013-09-24T10:18:15.997 回答
0

试试这个,我希望它是你需要的。如果不更新,我会更新结果。顺便说一句,这已经被问过几次了。

myFunc <- function(value) {
  if (value[1] == 1) {
    value[2] = 5;
    value[3] = 5;
    value[4] = 5 
  }
  # here you put you're if's
}

apply(data, 1, myFunc)
于 2013-09-24T09:31:41.780 回答