在 R/重新编码 NA 中组合调查项目 [英] Combining Survey Items in R/ Recoding NAs

查看:27
本文介绍了在 R/重新编码 NA 中组合调查项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表(来自多波调查),如下所示:

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

X1 X2
1  NA
NA  2
NA  NA

如何轻松地将其组合到第三个项目中,其中第三列始终采用列 X1 或 X2 的非 NA 值,并在两个值均为 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?

推荐答案

结合 Gavin 对 within 的使用和 Prasad 对 ifelse 的使用为我们提供了一个更简单的答案.

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))

不需要多个 ifelse 调用 - 当两个值都是 NA 时,您可以直接取其中一个值.

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

这篇关于在 R/重新编码 NA 中组合调查项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆