使用double for循环访问r中datafram中的元素

时间:2018-12-11 23:36:15

标签: r loops

我想使用双for来访问元素并将其填充在列表中。两个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"

1 个答案:

答案 0 :(得分:1)

没有任何循环

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