0

我有一个大型数据集,其中每一行可能有一个带有文本的单元格,而其余的都是空的。有没有办法将这些行子集在仅给定列中的文本而其余为空?

我知道我可以使用 eg tmp[tmp$A!="" & tmp$B=="" & tmp$C=="" & tmp$D=="",],但我有大约。我想为每列运行 30 列,这将是相当乏味的。我已经尝试了以下方法,但它的行为不符合预期。

tmp=data.frame(A=c("a","","","",""),
            B=c("","b","","",""),
            C=c("","","c","",""),
                D=c("","","","D",""))
#Attempting subsetting across multiple columns with tmp[,2:3]
tmp[tmp[,1]!="" & tmp[,2:3]=="",]
      A    B    C    D
1     a               
NA <NA> <NA> <NA> <NA>

#But it results in creating rows with na
tmp[tmp[,1]!="" & tmp[,2:4]=="",]
        A    B    C    D
1       a               
NA   <NA> <NA> <NA> <NA>
NA.1 <NA> <NA> <NA> <NA>

我只想结束的地方:

    A    B    C    D
 1       a               

然后将在 an 中使用ifelse(),因此如果 A 列中只有单元格带有文本,则给出 E 列文本 A,如果 B 列中只有文本给出 E 列文本 B

    A    B    C    D    E
    a                   A
         b              B
              c         C
                   d    D

建议?

4

1 回答 1

2

在您的示例数据框中,字符向量被转换为因子,因此您可以通过stringsAsFactors=FALSE在示例数据框中使用来删除 R 的默认行为

 tmp=data.frame(A=c("a","","","",""),
                    B=c("","b","","",""),
                    C=c("","","c","",""),
                    D=c("","","","D",""),stringsAsFactors=FALSE)

然后你可以得到你所期望的:

kk<-tmp[tmp[,1]!="",]
> kk
  A B C D
1 a   

ll<-tmp[tmp[,2]!="",]
> ll
  A B C D
2   b 


 tmp[1:4,"E"]<-names(is.na(c(tmp)))
 tmp
  A B C D    E
1 a          A
2   b        B
3     c      C
4       D    D
5         <NA>

na.omit(tmp)
  A B C D E
1 a       A
2   b     B
3     c   C
4       D D

..................................................... .....................
原始评论:

使用str(tmp)

 str(tmp)
'data.frame':   5 obs. of  4 variables:
 $ A: Factor w/ 2 levels "","a": 2 1 1 1 1
 $ B: Factor w/ 2 levels "","b": 1 2 1 1 1
 $ C: Factor w/ 2 levels "","c": 1 1 2 1 1
 $ D: Factor w/ 2 levels "","D": 1 1 1 2 1

所以,

levels(tmp[,1])
[1] ""  "a"

所以,你需要使用levels(tmp[,1]))==""

..................................................... .....................

于 2013-09-24T21:09:41.640 回答