首页 > 解决方案 > 奇怪的错误: 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")

标签: rdataframe

解决方案


它可能更容易使用subset

maschi <- subset(studenti, sesso == "M")

filterdplyr

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

推荐阅读