我想使用双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"
答案 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))