尝试编写函数时出现“包装时出错:必须用有效的下标向量对行进行子集化”

奥兹曼迪亚斯

我正在尝试将这段代码复制为一个函数。

它删除变量Q19中的所有NA观测值以及变量StartDate中的所有相关观测值。

timeperceptions <- timeperceptions[!(timeperceptions$StartDate >= '09/17/15' & is.na(timeperceptions$Q19)) & !(timeperceptions$StartDate <= '03/16/16' & is.na(timeperceptions$Q19)) ,]

我的功能看起来像这样

naremover <- function(df, col1, col2, time1, time2) {
  df[!(df$col1 >= 'time1' & is.na(df$col2)) & !(df$col1 <= 'time2' & is.na(df$col2)), ]

  }
testing2 <- naremover(timeperceptions, StartDate, Q19, 09/17/15, 03/16/16) 

它需要数据框,2个相对列和时间序列日期(将相对观测值限制在其中)。但是,当我调用它时,我会遇到这个错误

Error during wrapup: Must subset rows with a valid subscript vector.
ℹ Logical subscripts must match the size of the indexed input.
x Input has size 740 but subscript `&...` has size 0. 

我该怎么办才能补救?

罗纳克·沙
  • 编写函数时不要使用$引用特定的列,请使用[[
naremover <- function(df, col1, col2, time1, time2) {
  df[!(df[[col1]] >= time1 & is.na(df[[col2]])) & 
     !(df[[col1]] <= time2 & is.na(df[[col2]])), ]
}
  • 处理日期时,请始终确保您的数据属于日期类,而不是字符/因数类。
  • 将列名称作为字符传递给函数。
  • 通过time1time2日期类也是如此。
timeperceptions$StartDate <- as.Date(timeperceptions$StartDate, "%m/%d/%y")
timeperceptions$Q19 <- as.Date(timeperceptions$Q19, "%m/%d/%y")

testing2 <- naremover(timeperceptions, "StartDate", "Q19", 
                      as.Date('2015-09-17'), as.Date('2016-03-16')) 

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用knnImpute时在preProcess()中出现“错误:必须对具有有效下标向量的行进行子集化”

必须在dplyr :: anti_join()期间使用有效的下标向量对元素进行子集化

尝试编写自定义排序函数时出错

尝试编写单子函数时出错

循环有效,尝试 map-reduce 时出错

尝试编写Unity iOS插件时出现Malloc错误

尝试编写html文件时出现权限错误

尝试编码时出错

尝试编写C ++包装函数时无法将Numpy数组转换为Cython中的OpenCV Mat

生成有效的json递归javascript函数时出错

尝试发送第二个有效载荷后出现“解码有效载荷时出错”

尝试编写有效的代码以使用Kotlin更新背景色

在等待时出错,该等待仅在使用异步函数时对异步函数有效

尝试编译SASS代码时出错

尝试编辑电报消息时出错

尝试 CountIf 函数时出现“下标超出范围”错误

使用向量中的值和名称对数据框进行子集化的简单有效方法

尝试从有效的LatLng对象创建LatLngBounds对象时出错

代码仅在未包装在函数中时才有效

尝试编写回退实例时出现重叠实例错误

尝试编写返回某些数字的数学测试时出现问题

尝试编写图形时为什么会出现细分错误?

<function TextIOWrapper.close> 在尝试编写 HTML 页面时出现

当我尝试编写单元测试时出现断言错误

尝试编写通用节点元素时出现错误 2344 Typescript

尝试调用有效方法重载时出现奇怪的“未引用程序集”错误

尝试访问Ruby哈希时出现NoMethodError,但在irb中有效

我在尝试编写 set/get 函数时遇到加载器错误

Sails.js 尝试编辑和更新函数时出错