R:添加逻辑应用
R: adding logical to sapply
我正在尝试 运行 此代码:
check_zeros <- function(x) { # WIP
if (x == 0) {
!(df[gsub('\b0+','',format(as.Date(formation$study_start_dates_list[i]),'%m/%d/%Y')), names(x)] == df[gsub('\b0+','',format(as.Date(formation$study_end_dates_list[i]),'%m/%d/%Y')), names(x)])
}
}
remove_undesired_stocks2 <- function(n) {
i = 1
listofdfs_filtered <- list()
for (i in 1:n) {
a <- subset(average_returns, row.names(average_returns) == i)
b <- as.data.frame(sapply(subset(average_returns, row.names(average_returns) == i), function(x) all(x == 0 | is.nan(x) | check_zeros(x) )))
c <- a[, !b]
listofdfs_filtered[[i]] <- c
}
return(listofdfs_filtered)
}
错误如下:
Error in if (x == 0) { : missing value where TRUE/FALSE needed
我认为是因为有一个 NaN
进入 check_zeros
函数的 x == 0
。
有什么方法可以克服这个问题吗?提前致谢。
我想我自己解决了:
check_zero 函数的构造方式不能接受长度 > 1 的对象。更具体地说,if
中的逻辑不能使用长度 > 1[=26= 的对象].
由于我在 length > 1
中使用对象,因此出现错误
你在这种情况下应该使用ifelse
:
check_zeros <- function(x) {
ifelse(x == 0, (df[gsub('\b0+','',format(as.Date(formation$study_start_dates_list[i]),'%m/%d/%Y')), names(x)] == df[gsub('\b0+','',format(as.Date(formation$study_end_dates_list[i]),'%m/%d/%Y')), names(x)]), FALSE)
}
干杯。
我正在尝试 运行 此代码:
check_zeros <- function(x) { # WIP
if (x == 0) {
!(df[gsub('\b0+','',format(as.Date(formation$study_start_dates_list[i]),'%m/%d/%Y')), names(x)] == df[gsub('\b0+','',format(as.Date(formation$study_end_dates_list[i]),'%m/%d/%Y')), names(x)])
}
}
remove_undesired_stocks2 <- function(n) {
i = 1
listofdfs_filtered <- list()
for (i in 1:n) {
a <- subset(average_returns, row.names(average_returns) == i)
b <- as.data.frame(sapply(subset(average_returns, row.names(average_returns) == i), function(x) all(x == 0 | is.nan(x) | check_zeros(x) )))
c <- a[, !b]
listofdfs_filtered[[i]] <- c
}
return(listofdfs_filtered)
}
错误如下:
Error in if (x == 0) { : missing value where TRUE/FALSE needed
我认为是因为有一个 NaN
进入 check_zeros
函数的 x == 0
。
有什么方法可以克服这个问题吗?提前致谢。
我想我自己解决了:
check_zero 函数的构造方式不能接受长度 > 1 的对象。更具体地说,if
中的逻辑不能使用长度 > 1[=26= 的对象].
由于我在 length > 1
中使用对象,因此出现错误
你在这种情况下应该使用ifelse
:
check_zeros <- function(x) {
ifelse(x == 0, (df[gsub('\b0+','',format(as.Date(formation$study_start_dates_list[i]),'%m/%d/%Y')), names(x)] == df[gsub('\b0+','',format(as.Date(formation$study_end_dates_list[i]),'%m/%d/%Y')), names(x)]), FALSE)
}
干杯。