首页 > 解决方案 > 如果,那么 R 中的语句

问题描述

我正在自学 R 并试图弄清楚如何正确编写 if, then 语句。我有一个人口统计数据,我想根据婚姻状况为家庭中的最高学历创建一个变量。如果数据编码为 0、3 或 7,则它是单亲(妈妈)家庭,然后将使用母亲的学位。但是,如果是 1、2、4、5 或 6,我想使用任何一个看护人的最高学历。

> ExcelData <-df
> marital <- c(1, 0, 1, 5, 7, 2, NA, 1)
> education <- c("10", "12", "13", "14", "16", "18", "12", "14")
> education_partner <- c("11", "18", "10", "14", "11", "12", "16", "16")

我写了这个并且它有效,创建了一个具有母性教育的新 df,但我不知道如何写它,当它是 1、2、4、5 或 6 时,它会打印出教育或教育伙伴的更大价值。任何意见是极大的赞赏!!

if(ExcelData$marital =  0 | 3:7 )
  hhHighestDegree <- (ExcelData$education)

标签: rif-statementpipe

解决方案


if/else未矢量化。我们可以使用ifelse或创建一个逻辑向量,然后将基于逻辑向量的“教育”列的子集分配给新对象“hhHighestDegree”。

根据显示的代码,我们需要提取“婚姻”值为 0 或 3:7 的“教育”值。因此,我们可以使用%in%创建逻辑向量 (%in%也将返回与比较运算符 ( , , )不同FALSE的值NA><==

i1 <- ExcelData$marital %in% c(0, 3:7)
hhHighestDegree <- ExcelData$education[i1]

或者,如果我们更喜欢使用>with|

i1 <- with(ExcelData, (marital == 0| (marital >=3 & marital<=7)) & 
            !is.na(marital))
hhHighestDegree <- ExcelData$education[i1]

数据

ExcelData <- structure(list(marital = c(1, 0, 1, 5, 7, 2, NA, 1), 
education = c("10", 
"12", "13", "14", "16", "18", "12", "14"), education_partner = c("11", 
"18", "10", "14", "11", "12", "16", "16")), 
class = "data.frame", row.names = c(NA, 
-8L))

推荐阅读