r - 奇怪的错误: if () { 中的错误:需要 TRUE/FALSE 的缺失值
问题描述
我有以下名为 studenti 的数据框:
当我尝试运行以下代码时:
maschi = data.frame()
indice = 0
for (i in seq_along(studenti$sesso)) {
if (studenti$sesso[i] == "M") {
indice = indice + 1
maschi[indice,] <- studenti[i,]
}
}
出现以下错误“if () { 中的错误:需要 TRUE/FALSE 的缺失值”。
我的目标是在数据框 maschi 中仅复制数据框 studenti 的行,使得 sesso=M。
编辑
编辑:输入输出
structure(list(sesso = c("F", "M", "M", "M", "M"), altezza = c(168,
182, 176, 193, 178), peso = c(60, 75, 72, 95, 68), scarpe = c(41,
43, 45, 45, 45), caso = c(7, 9, 5, 6, 7), matricola = c(1, -1,
-1, -1, 6), mese = c(11, 5, 9, 5, 7), giorno = c(7, 2, 29, 8,
12)), row.names = c(NA, 5L), class = "data.frame")
解决方案
它可能更容易使用subset
maschi <- subset(studenti, sesso == "M")
或filter
从dplyr
library(dplyr)
studenti %>%
filter(sesso == "M")
for
循环可以用rbind
maschi <- studenti[0,]
for(i in seq_len(nrow(studenti))) {
if(studenti$sesso[i] == "M" & !is.na(studenti$sesso[i])) {
maschi <- rbind(maschi, studenti[i,])
}
}
此外,在 OP 的代码中,我们只需要
maschi <- studenti[0,]
indice = 0
for (i in seq_along(studenti$sesso)) {
if (studenti$sesso[i] == "M" & !is.na(studenti$sesso[i])) {
indice = indice + 1
maschi[indice,] <- studenti[i,]
}
}
-输出
> maschi
sesso altezza
2 M 182
3 M 176
4 M 193
- 使用 OP 的更新数据进行更新
> maschi
sesso altezza peso scarpe caso matricola mese giorno
2 M 182 75 43 9 -1 5 2
3 M 176 72 45 5 -1 9 29
4 M 193 95 45 6 -1 5 8
5 M 178 68 45 7 6 7 12
数据
studenti <- data.frame(sesso = c("F", "M", "M", "M"), altezza = c(168, 182, 176, 193))
推荐阅读
- android - 在 Fragment 附加到 FragmentManager 之前,无法执行 onGetLayoutInflater()
- swift - 静态 UITableViewController 之上的 UIView
- ios - 如何在没有 CocoaPods 的情况下安装 Almofire
- php - 保存 Wordpress 主题选项输入值
- r - R CRAN 存储库不适用于 Ubuntu 18.04 LTS
- android - Oreo 8.0 上的 AlertDialog 中的按钮颜色问题
- javascript - 反应:使字段可编辑,也可以从外部更新
- vbscript - 如何将循环中读取的行的子字符串分配给单独的变量?
- redux - 未调用 Redux saga 函数
- webpack - Webpack完成后如何删除输出的index.js?