我正在尝试将这段代码复制为一个函数。
它删除变量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]])), ]
}
time1
和time2
日期类也是如此。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] 删除。
我来说两句