Combining Survey Items in R/ Recoding NAs

一个人想着一个人 提交于 2019-12-07 17:21:39

问题


I have two lists (from a multi-wave survey) that look like this:

X1 X2
1  NA
NA  2
NA  NA

How can I easily combine this into a third item, where the third column always takes the non-NA value of column X1 or X2, and codes NA when both values are NA?


回答1:


Combining Gavin's use of within and Prasad's use of ifelse gives us a simpler answer.

within(df, x3 <- ifelse(is.na(x1), x2, x1))

Multiple ifelse calls are not needed - when both values are NA, you can just take one of the values directly.




回答2:


Another way using ifelse:

df <- data.frame(x1 = c(1, NA, NA, 3), x2 = c(NA, 2, NA, 4))
> df
  x1 x2
1  1 NA
2 NA  2
3 NA NA
4  3  4

> transform(df, x3 = ifelse(is.na(x1), ifelse(is.na(x2), NA, x2), x1))
  x1 x2 x3
1  1 NA  1
2 NA  2  2
3 NA NA NA
4  3  4  3



回答3:


This needs a little extra finesse-ing due to the possibility of both X1 and X2 being NA, but this function can be used to solve your problem:

foo <- function(x) {
    if(all(nas <- is.na(x))) {
        NA
    } else {
        x[!nas]
    }
}

We use the function foo by applying it to each row of your data (here I have your data in an object named dat):

> apply(dat, 1, foo)
[1]  1  2 NA

So this gives us what we want. To include this inside your object, we do this:

> dat <- within(dat, X3 <- apply(dat, 1, foo))
> dat
  X1 X2 X3
1  1 NA  1
2 NA  2  2
3 NA NA NA



回答4:


You didn't say what you wanted done when both were valid numbers, but you can use either pmax or pmin with the na.rm argument:

 pmax(df$x1, df$x2, na.rm=TRUE)
# [1]  1  2 NA  4


来源:https://stackoverflow.com/questions/4658538/combining-survey-items-in-r-recoding-nas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!