R-在不删除NA值的情况下拆分数据帧 [英] R - split data frame without removing NA values

查看:102
本文介绍了R-在不删除NA值的情况下拆分数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有df:

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

我想将其拆分为2个dfs ...一个仅包含body_part-"head",另一个仅包含其他内容.即

And I want to split it into 2 dfs... One with only body_part - "head" and the other with everything else. I.e.

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

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

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

Can I do that without dropping the NA rows? (I know I can do it if I fill the NAs with a string, but is there a way that avoids that step?)

推荐答案

来自?`%in%`:

%in%"永远不会返回"NA",这使得它在 如果"条件.

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

这篇关于R-在不删除NA值的情况下拆分数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆