R:用指标值替换预测值

时间:2013-12-02 19:27:27

标签: r matrix replace machine-learning subset

我有一个19万密耳的矩阵预测IDRating的观察结果。我想替换实际RatingID的预测Rating

以下是我想要完成的演示:

train <- data.frame(1:10,c(1,2,NA,4,5,NA,7,8,NA,10))
names(train) <- c("ID", "Rating")
pred <- data.frame(1:10, c(1,1,3,4,2,4,5,6,7,1))
names(pred) <- c("ID", "Rating")

我希望最后的预测是:

pred <- data.frame(1:10, c(1,2,3,4,5,4,7,8,7,10))
names(pred) <- c("ID", "Rating")

有什么建议吗?

尝试:

1 个答案:

答案 0 :(得分:2)

只需使用[]括号和is.na对数据进行分组。

> train$Rating[is.na(train$Rating)] = pred$Rating[is.na(train$Rating)]
> train
   ID Rating
1   1      1
2   2      2
3   3      3
4   4      4
5   5      5
6   6      4
7   7      7
8   8      8
9   9      7
10 10     10

或者,走另一条路:

> pred$Rating[!is.na(train$Rating)] = train$Rating[!is.na(train$Rating)]
> pred
   ID Rating
1   1      1
2   2      2
3   3      3
4   4      4
5   5      5
6   6      4
7   7      7
8   8      8
9   9      7
10 10     10