首页 > 解决方案 > 使用双 for 循环访问 r 中数据帧中的元素

问题描述

我想使用 doublefor来访问一个元素并将其填充到列表中。两个for循环,包括第一个基于列ID和第二个基于列,sem然后用于if检查课程是否可以"math" 说:

df:
ID  sem  course
10  1    "math"
10  1    "phys"
10  1    "other"
10  2    "math"
10  2    "phys2"
10  2    "chem"
11  1    "other"
11  2    "math"

这是sodu代码

mylist=list(NA)
for in each ID {
   for j in each sem{
      check the element course=='math'{
          insert it into mylist (or do some other stuffs here)
 }}}

我的目的是使用循环来检查列的每个元素。结果:

mylist
"math","math", "math"

标签: rloops

解决方案


没有任何循环怎么办

rep("math",sum(df$course == "math"))
# returns
[1] "math" "math" "math"

df <- structure(list(ID = c(10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L), 
sem = c(1, 1, 1, 2, 2, 2, 1, 2), course = c("math", "phys", 
"other", "math", "phys2", "chem", "other", "math")), class = "data.frame", row.names = c(NA, 
-8L))

推荐阅读