Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何在另一个向量上使用条件来创建新向量?_R_Loops - Fatal编程技术网

R 如何在另一个向量上使用条件来创建新向量?

R 如何在另一个向量上使用条件来创建新向量?,r,loops,R,Loops,我有一个向量,my_class,它由等级组成。我正在尝试生成一个新的向量,top_grades,该向量由my_class中大于或等于85的分数填充。 我写了下面的代码,但是top_grades向量的大小与my_class向量的大小相同,所有85岁以下的成绩都返回为NA。我认为这是因为在构建向量时,top_grades的一些指数没有给出任何值 my_class = c(84, 85, 90) #sample vector top_grades = c() #create vector for (i

我有一个向量,
my_class
,它由等级组成。我正在尝试生成一个新的向量,
top_grades
,该向量由
my_class
中大于或等于85的分数填充。 我写了下面的代码,但是
top_grades
向量的大小与
my_class
向量的大小相同,所有85岁以下的成绩都返回为NA。我认为这是因为在构建向量时,
top_grades
的一些指数没有给出任何值

my_class = c(84, 85, 90) #sample vector
top_grades = c() #create vector
for (i in 1:length(my_class)) { #iterate for each index in the length of my_class
  if (my_class[i] >= 85) {
    top_grades[i] <- my_class[i] #the value of top_grades at index i is the value of my_class at index i
  } else {
    next #go to next index if the value of the grade at that index is lower than 85
  }
}
我的问题:有没有一种更优雅的方法来编写这个循环,在没有NA的情况下构建
top\u grades
向量

> top_grades<-my_class[my_class>=85]
> top_grades
[1] 85 90

这完全等同于我的单线版本)

您可以使用

top_grades <- my_class[my_class >= 85]

哇!我觉得自己像个傻瓜。谢谢你的明确回答!
high<-my_class>=85
top_grades<-my_class[high]
top_grades <- my_class[my_class >= 85]
which(my_class >= 85)