R:用向量中的项替换NA [英] R: replace NA with item from vector
本文介绍了R:用向量中的项替换NA的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试用相似组的平均值替换数据中的某些缺失值.
I am trying to replace some missing values in my data with the average values from a similar group.
我的数据如下:
X Y
1 x y
2 x y
3 NA y
4 x y
我希望它看起来像这样:
And I want it to look like this:
X Y
1 x y
2 x y
3 y y
4 x y
我写了这个,它奏效了
for(i in 1:nrow(data.frame){
if( is.na(data.frame$X[i]) == TRUE){
data.frame$X[i] <- data.frame$Y[i]
}
}
但是我的data.frame长近一百万行,并且for/if语句非常慢.我想要的是类似的东西
But my data.frame is almost half a million lines long, and the for/if statements are pretty slow. What I want is something like
is.na(data.frame$X) <- data.frame$Y
但这会导致大小不匹配的错误.似乎应该有一个执行此操作的命令,但是我在SO或R帮助列表上找不到它.有什么想法吗?
But this gets a mismatched size error. It seems like there should be a command that does this, but I cannot find it here on SO or on the R help list. Any ideas?
推荐答案
ifelse
是你的朋友.
使用Dirk的数据集
df <- within(df, X <- ifelse(is.na(X), Y, X))
这篇关于R:用向量中的项替换NA的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文