r:在 `sapply` 循环中保留警告作为向量
r: Retaining warnings in `sapply` loop as a vector
我正在使用我自己的函数转换我的数据,如下所示:
my_df %>% [...] %>%
mutate(my_result = sapply(id_column, my_function))
此处,my_function
将对 returns 数值结果的每一行执行一些计算。该函数不能(轻易地)被矢量化,这就是我依赖 sapply 的原因。到目前为止,还不错。
有时,my_function
会发出警告,表示对特定结果持保留态度。
我想捕获这些警告,并将它们附加到新列中的数据框。预期结果:
id_column | ... | result | warnings
1 | ... | result1 | NA
2 | ... | result2 | "Warning: something happened on id 2"
3 | ... | result3 | NA
我怎样才能做到这一点?
我会改用 lapply
,这样您就可以 return 每次有两列的单行 data.frame
和再次 rbind
该数据框列表最后。
df <- data.frame(a=runif(20)-0.5)
f <- function(x) {
tryCatch ({
data.frame(result=log(x), warning=NA)
}, warning = function(w) {
data.frame(result=suppressWarnings(log(x)), warning=w$message)
})
}
res <- cbind(df, do.call(rbind, lapply(df$a, f)))
@mpjdem 的答案的替代方案,但与 sapply
保持一致:
tryCatch.W.E
returns一个列表
>> tryCatch.W.E(log(-5))
$value
[1] NaN
$warning
<simpleWarning in log(-5): NaNs produced>
结合sapply
这会产生一个矩阵,原始任务可以通过
解决
my_df %>% cbind(t(sapply(.$id_column, function(x) {tryCatch.W.E(my_function(x))})))
我正在使用我自己的函数转换我的数据,如下所示:
my_df %>% [...] %>%
mutate(my_result = sapply(id_column, my_function))
此处,my_function
将对 returns 数值结果的每一行执行一些计算。该函数不能(轻易地)被矢量化,这就是我依赖 sapply 的原因。到目前为止,还不错。
有时,my_function
会发出警告,表示对特定结果持保留态度。
我想捕获这些警告,并将它们附加到新列中的数据框。预期结果:
id_column | ... | result | warnings
1 | ... | result1 | NA
2 | ... | result2 | "Warning: something happened on id 2"
3 | ... | result3 | NA
我怎样才能做到这一点?
我会改用 lapply
,这样您就可以 return 每次有两列的单行 data.frame
和再次 rbind
该数据框列表最后。
df <- data.frame(a=runif(20)-0.5)
f <- function(x) {
tryCatch ({
data.frame(result=log(x), warning=NA)
}, warning = function(w) {
data.frame(result=suppressWarnings(log(x)), warning=w$message)
})
}
res <- cbind(df, do.call(rbind, lapply(df$a, f)))
@mpjdem 的答案的替代方案,但与 sapply
保持一致:
tryCatch.W.E
returns一个列表
>> tryCatch.W.E(log(-5))
$value
[1] NaN
$warning
<simpleWarning in log(-5): NaNs produced>
结合sapply
这会产生一个矩阵,原始任务可以通过
my_df %>% cbind(t(sapply(.$id_column, function(x) {tryCatch.W.E(my_function(x))})))