简体   繁体   English

R中的subset.data.frame

[英]subset.data.frame in R

I have a data frame of raw data: 我有一个原始数据的数据框:

raw <- data.frame(subj = c(1,1,1,2,2,2,3,3,3,4,4,4),
                   blah = c(0,0,0,1,1,1,1,0,1,0,0,0))

From it, I want to remove the bad subj. 从它,我想删除坏的主题。

badsubj <- c(1,4)  
trim <- subset.data.frame(raw, subj != badsubj)  

But for some reason, all the badsubj values are not removed: 但是由于某些原因,并不会删除所有badsubj值:

   subj blah
2     1    0
4     2    1
5     2    1
6     2    1
7     3    1
8     3    0
9     3    1
11    4    0

What am I doing wrong? 我究竟做错了什么? Obersvations 2 and 11 should be excluded because they are members of badsubj. 意见2和11应该被排除,因为它们是badsubj的成员。

raw[!raw$subj %in% badsubj, ] 

错误使用!=

The problem is that subj and badsubj do not have the same length. 问题是subj和badsubj的长度不同。 Therefore badsubj will be recycled until both vectors have the same length. 因此badsubj将被回收直到两个向量的长度相同。 Then your code compares elementwise the values in the output below. 然后,您的代码逐元素比较下面输出中的值。

     subj badsubj
 1     1    1
 2     1    4
 3     1    1
 4     2    4
 5     2    1
 6     2    4
 7     3    1
 8     3    4
 9     3    1
 10    4    4
 11    4    1
 12    4    4

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM