我有一個類似于 in 的函式R,它使用 adf作為主要引數。但是,df 可能為空,如果我使用lapply
eg運行該函式,我想跳過那些lapply(FileNames, function(y) my.function(y))
我的功能看起來像這樣
my.function <- function(table) {
file <- read.csv(table, header=T)
if(nrow(table) == 0)
{next}
#skip the df if is empty and stop processing that df
#do more stuffs if not empty
}
到目前為止,我已經嘗試過這個,但是如果資料框為空,整個程序就會崩潰,有什么提示嗎?
uj5u.com熱心網友回復:
假設您有一個像這樣的資料框串列:
my_list <- list(data.frame(a = 1:3, b = 1:3),
data.frame(a = c(), b = c()),
data.frame(a = 1:5, b = 1:5))
my_list
#> [[1]]
#> a b
#> 1 1 1
#> 2 2 2
#> 3 3 3
#>
#> [[2]]
#> data frame with 0 columns and 0 rows
#>
#> [[3]]
#> a b
#> 1 1 1
#> 2 2 2
#> 3 3 3
#> 4 4 4
#> 5 5 5
那么你的函式可能是這樣的:
my_func <- function(df) {
# return NULL and stop function if dataframe has zero rows
if(nrow(df) == 0) return(NULL)
# Do work on dataframes with one or more rows
data.frame(sum = df$a df$b)
}
所以現在如果lapply我們得到:
result <- lapply(my_list, my_func)
result
#> [[1]]
#> sum
#> 1 2
#> 2 4
#> 3 6
#>
#> [[2]]
#> NULL
#>
#> [[3]]
#> sum
#> 1 2
#> 2 4
#> 3 6
#> 4 8
#> 5 10
如果您想NULL從串列中洗掉值,您可以執行以下操作:
result[!sapply(result, is.null)]
#> [[1]]
#> sum
#> 1 2
#> 2 4
#> 3 6
#>
#> [[2]]
#> sum
#> 1 2
#> 2 4
#> 3 6
#> 4 8
#> 5 10
更新
要在遇到空檔案時在函式中包含警告訊息,我們可以執行以下操作:
my_func <- function(df) {
# return NULL and stop function if dataframe has zero rows
if(nrow(df) == 0) {
warning("This file is empty")
return(NULL)
}
# Do work on dataframes with one or more rows
data.frame(sum = df$a df$b)
}
由reprex 包( v2.0.0 )于 2021 年 11 月 15 日創建
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358000.html
上一篇:所有正偶數的總和
