r - 如果,那么 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)
解决方案
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))
推荐阅读
- python - Python Pandas:计算正数的连续窗口计数
- elasticsearch - Flink 弹性搜索源连接器
- android - 旋转设备时如何不丢失 EditText 内容 - EditText 在 RecyclerView 项目内
- perl - Perl如何在关键字(匹配)前面引入文本并将其余部分保留在文件中
- typescript - 使用 Angular 快速地 iframe
- excel - 根据特定值更新表中的值
- terraform - 如果映射键为空字符串,则条件动态块
- birt - 如何创建全局变量以及如何将数据集值设置为全局变量
- javascript - jquery post方法的问题
- javascript - 如何将 d3.event 作为子模块导入反应应用程序以使用 d3.event.pageX