R - 在不删除 NA 值的情况下拆分数据框

R - split data frame without removing NA values

如果我有df:

letter    body_part
    a     head
    b     head
    c     NA
    d     NA
    e     left_foot

我想把它分成 2 个 dfs...一个只有 body_part - "head",另一个有其他所有东西。即

list <- split(df, df$body_part == 'head')

我可以在不删除 NA 行的情况下这样做吗? (我知道如果我用字符串填充 NA 就可以做到,但是有没有办法避免这一步?)

> ind <- df$body_part == 'head'
> ind[is.na(ind)] <- FALSE
> split(df, ind)
$`FALSE`
# A tibble: 3 x 2
  letter body_part
   <chr>     <chr>
1      c      <NA>
2      d      <NA>
3      e left_foot

$`TRUE`
# A tibble: 2 x 2
  letter body_part
   <chr>     <chr>
1      a      head
2      b      head

来自?`%in%`

That ‘%in%’ never returns ‘NA’ makes it particularly useful in ‘if’ conditions.

# just to show how the `==` comparison compares  
> df$s_col <- df$body_part == 'head'

> split(df, df$body_part %in% 'head')
$`FALSE`
  letter body_part s_col
3      c      <NA>    NA
4      d      <NA>    NA
5      e left_foot FALSE

$`TRUE`
  letter body_part s_col
1      a      head  TRUE
2      b      head  TRUE

您可以将 split()f 参数转换为因子,同时不排除 NA 值。

df <- read.table(h= T, strin = F, text = "
letter    body_part
    a     head
    b     head
    c     NA
    d     NA
    e     left_foot")

split(df, factor(df$body_part,exclude = NULL))
#> $head
#>   letter body_part
#> 1      a      head
#> 2      b      head
#> 
#> $left_foot
#>   letter body_part
#> 5      e left_foot
#> 
#> $<NA>
#>   letter body_part
#> 3      c      <NA>
#> 4      d      <NA>
split(df, factor(df$body_part,exclude = NULL) == 'head')
#> $`FALSE`
#>   letter body_part
#> 3      c      <NA>
#> 4      d      <NA>
#> 5      e left_foot
#> 
#> $`TRUE`
#>   letter body_part
#> 1      a      head
#> 2      b      head

reprex package (v0.3.0)

于 2019-10-14 创建