r - 如何在满足条件的所有行之前只选择前 10 行?
问题描述
我在 R 环境中有一个时间序列数据集。变量 CB_Day 在某些日期等于 MPD,在大多数日期等于 0。
我想删除除 MPD 天和前 10 天之外的所有行。
我尝试过subset、head()和tail(),但它们没有用。
有人能告诉我根据我在 R 中的条件删除记录的正确命令是什么吗?
结果应该是包含所有其他列的整个表。只有行需要被删除。
解决方案
如果我做对了,那么这样的事情应该会有所帮助......
# create data where CB_Day is always 0 (please provide reproducible data next time)
df <- data.frame(MPD = 1:100, CB_Day = rep(0, 100))
# sometimes CB_Day is same as MPD
df$CB_Day[c(20, 70)] <- df$MPD[c(20, 70)]
# Find where both are same
same <- which(df$MPD== df$CB_Day)
# create vectors with "10 rows before CB_Day and MPD are same" to the row where they are same
keep <- sapply(same, function(x){(x-10):x})
# make it a vector instead of a matrix
keep <- unlist(keep)
# select the rows
df[keep, ]
推荐阅读
- reactjs - 当我尝试遵循 ReactJS.org 文档时出错
- google-apps-script - 您无权调用 Ui.showModalDialog 错误,但 Scope 存在,并且对话框仍然显示
- c++ - 如何将打包的参数类型放入元组中?
- c# - 每 5 分钟从 C# Web 服务向外部 API 发出少量请求,而不会耗尽所有套接字
- vtk - VTK:角落而不是中间的小舒适
- python - ImportError:导入dogtail时没有名为gconf的模块
- sql-server - 尝试将脚本结果写入表时出错
- swift - Swift:在 UIView 中添加的按钮不可点击
- python - 如何在 Python 中删除共享的 RawArray 以释放内存空间
- python - 前 2 个选项的 tkinter optionmenu keyerror