R - Purrr - 使用 map() 进行切片,或者:如何根据 NA 切片不同长度的 tibbles 列表?
R - Purrr - Slicing using map(), or: How to slice list of tibbles of varying lengths based on NAs?
我正在尝试弄清楚如何根据 non-NA 的首次出现对不同长度的 tibbles 列表进行切片或子集化。我所有的小标题都有不同的维度和许多 NA,但所有的共同点是它们在我需要删除的第一行中有一些 NA。
我只对在保留所有后续行的同时删除第一行感兴趣。
我创建了一个代表我的数据的代表:
tbl <- tibble(
first = c(NA, 1, 2, 3, NA),
second = c(NA, 1, NA, 3, NA),
third = c(NA, 1, 2, NA, NA)
)
lst <- list(
list1 = tbl,
list2 = tbl,
list3 = tbl
)
lst
$list1
# A tibble: 5 x 3
first second third
<dbl> <dbl> <dbl>
1 NA NA NA
2 1 1 1
3 2 NA 2
4 3 3 NA
5 NA NA NA
$list2
# A tibble: 5 x 3
first second third
<dbl> <dbl> <dbl>
1 NA NA NA
2 1 1 1
3 2 NA 2
4 3 3 NA
5 NA NA NA
$list3
# A tibble: 5 x 3
first second third
<dbl> <dbl> <dbl>
1 NA NA NA
2 1 1 1
3 2 NA 2
4 3 3 NA
5 NA NA NA
我尝试将 map()
与 which.min()
和 is.na()
结合使用,以尝试根据 non-NA 的第一个实例进行切片,但无法使其工作.
sliced <- map(lst, slice, which.min(is.na):nrow())
我得到的只是以下错误:
Error in which.min(is.na) :
cannot coerce type 'builtin' to vector of type 'double'
有办法解决这个问题吗?
is.na
需要一个向量。您可能需要将特定列传递给它。
例如,使用第一列你可以做 -
library(dplyr)
library(purrr)
map(lst, ~.x %>% slice(which.max(!is.na(.[[1]])) : n()))
#$list1
# A tibble: 4 x 3
# first second third
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 2 NA 2
#3 3 3 NA
#4 NA NA NA
#$list2
# A tibble: 4 x 3
# first second third
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 2 NA 2
#3 3 3 NA
#4 NA NA NA
#$list3
# A tibble: 4 x 3
# first second third
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 2 NA 2
#3 3 3 NA
#4 NA NA NA
我正在尝试弄清楚如何根据 non-NA 的首次出现对不同长度的 tibbles 列表进行切片或子集化。我所有的小标题都有不同的维度和许多 NA,但所有的共同点是它们在我需要删除的第一行中有一些 NA。
我只对在保留所有后续行的同时删除第一行感兴趣。
我创建了一个代表我的数据的代表:
tbl <- tibble(
first = c(NA, 1, 2, 3, NA),
second = c(NA, 1, NA, 3, NA),
third = c(NA, 1, 2, NA, NA)
)
lst <- list(
list1 = tbl,
list2 = tbl,
list3 = tbl
)
lst
$list1
# A tibble: 5 x 3
first second third
<dbl> <dbl> <dbl>
1 NA NA NA
2 1 1 1
3 2 NA 2
4 3 3 NA
5 NA NA NA
$list2
# A tibble: 5 x 3
first second third
<dbl> <dbl> <dbl>
1 NA NA NA
2 1 1 1
3 2 NA 2
4 3 3 NA
5 NA NA NA
$list3
# A tibble: 5 x 3
first second third
<dbl> <dbl> <dbl>
1 NA NA NA
2 1 1 1
3 2 NA 2
4 3 3 NA
5 NA NA NA
我尝试将 map()
与 which.min()
和 is.na()
结合使用,以尝试根据 non-NA 的第一个实例进行切片,但无法使其工作.
sliced <- map(lst, slice, which.min(is.na):nrow())
我得到的只是以下错误:
Error in which.min(is.na) :
cannot coerce type 'builtin' to vector of type 'double'
有办法解决这个问题吗?
is.na
需要一个向量。您可能需要将特定列传递给它。
例如,使用第一列你可以做 -
library(dplyr)
library(purrr)
map(lst, ~.x %>% slice(which.max(!is.na(.[[1]])) : n()))
#$list1
# A tibble: 4 x 3
# first second third
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 2 NA 2
#3 3 3 NA
#4 NA NA NA
#$list2
# A tibble: 4 x 3
# first second third
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 2 NA 2
#3 3 3 NA
#4 NA NA NA
#$list3
# A tibble: 4 x 3
# first second third
# <dbl> <dbl> <dbl>
#1 1 1 1
#2 2 NA 2
#3 3 3 NA
#4 NA NA NA