代码之家  ›  专栏  ›  技术社区  ›  Cina

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

  •  0
  • Cina  · 技术社区  · 6 年前

    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"
    

    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 回复  |  直到 6 年前
        1
  •  1
  •   niko    6 年前

    不带任何环怎么样

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