用NA值替换列 [英] Subsetting out Columns with NA values

查看:63
本文介绍了用NA值替换列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此类似的数据帧(不完全是这个),我想将其作为子集...我想删除前两列,后两列以及所有具有NA值的列...

I have a dataframe similar to this (not exactly this) that I'm trying to subset... i want to remove the first two columns, the last two columns, and all columns with NA values...

df <- read.table(text="
          a     b    c    d      e      f       g      h
          1     5    6    NA     4      NA      7     9
          3     2    8    NA     9      NA      4     3
          6     5    2    NA     6      NA      1     1
     ",header=TRUE,stringsAsFactors = FALSE)

到目前为止,我只走了这么远:

So far I only got this far:

df[, (3:(ncol(df)-2))]

仅删除前两个和后两个...,但是我不知道如何使用NA删除列

which only removes the first two and the last two... but I cant figure out how to remove columns with NA

推荐答案

我们可以使用 colSums 和sequence来创建逻辑向量来对列进行子集

We can use colSums and sequence to create a logical vector to subset the columns

i1 <- seq_along(df)
df[(!i1 %in% c(1:2, tail(i1,2))) & !colSums(is.na(df))]
#  c e
#1 6 4
#2 8 9
#3 2 6

这篇关于用NA值替换列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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