R 为列编制索引时如何使用向量?

R 为列编制索引时如何使用向量?,r,R,基本上,我有一个向量: 注意,泰坦尼克号是一个参加泰坦尼克号的人的数据框 femalesurvivors_1 <- thetitanic[(thetitanic$Sex=="female") & (thetitanic$Survived==1) & (thetitanic$PClass=="1st"),] femalesurvivors_1=18) 我一直在尝试一些形式的代码,但我不断得到错误。 x=18)] 错误显示:1:在Ops.factor(左、右)中:“&”对于f

基本上,我有一个向量:

注意,泰坦尼克号是一个参加泰坦尼克号的人的数据框

femalesurvivors_1 <- thetitanic[(thetitanic$Sex=="female") & (thetitanic$Survived==1) & (thetitanic$PClass=="1st"),]
femalesurvivors_1=18)

我一直在尝试一些形式的代码,但我不断得到错误。
x=18)]

错误显示:1:在Ops.factor(左、右)中:“&”对于factor没有意义

当我做这些时,我能通过向量吗?或者我需要创建一个新的向量并重复代码

我试图返回第一班18岁以上女性幸存者的价值


我是个笨蛋。。任何帮助都将不胜感激。谢谢。

您可以创建一个条件的逻辑向量,并对其进行求和

sum(with(thetitanic, 
    Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18), na.rm = TRUE)
使用
子集

nrow(subset(thetitanic, Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18))
或者使用
dplyr
使用
filter

library(dplyr)

thetitanic %>%
  filter(Survived == 1 & Sex == "female" & Pclass == 1 & Age >= 18) %>%
   nrow

这将返回18岁以上一等女性幸存者的数量。如果需要这些条目,请从
filter
subset
函数中删除
nrow

带有
数据表的选项

library(data.table)
nrow(setDT(thetitanic)[Survived == 1 & Sex == "Female" & Pclass == 1 & Age >= 18])

您可能想分享更多的信息,比如数据是什么样子的,您收到了哪些错误消息,也许最重要的是,您的预期结果是什么样子的?