r - 使用双 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"
解决方案
没有任何循环怎么办
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))
推荐阅读
- python-3.x - KeyError: 'access_token' 在 OAuth 2.0 身份验证期间使用 Spotify API
- elasticsearch - ElasticSearch 的重新索引 api 完成后,我的目标索引的状态是什么?
- unity3d - 如何使特定的预制件在按下按钮时旋转?
- javascript - 使用 Firestore REST API 在结构化查询中设置“orderBy”
- java - Spring 将 fixedRateString 安排为 Duration
- php - PHP mysqli 子查询返回 Impossible WHERE 在读取 const 表后注意到
- html - 如何删除导航下方不需要的空格?
- css - 即使删除规则,如何完成动画?
- python - Seaborn barplot 图例标签失去颜色
- swift - 访问已使用 Padding 扩展的 CVPixelBuffer 之外的像素