【问题标题】:subsetting data in R from another vector (exclusion) [duplicate]从另一个向量(排除)[重复]中对R中的数据进行子集化
【发布时间】:2017-07-12 19:30:35
【问题描述】:

我有一个包含以下元素的数据框,我想要一个记录子集。

location <- c('london', 'london','london', 'newyork' ,'newyork', 'paris', 'delhi')
year<- c(1990, 1991, 1992, 2001, 2002, 2003,2001)

df<- data.frame(location,year)

我有一个向量说

x<- c('newyork', 'delhi')

我想对数据框进行子集化,以便最终数据框包含除 x 中未列出的位置之外的所有元素。我想创建一个测试数据框,我试过这个

 test1 <- df[df$location %in% c('newyork','delhi'), ] 

它给了我相反的结果。有人可以帮忙吗?

我期待这样的输出:

       location year 
       london    1990
       london    1991
       london    1992
       paris     2003

【问题讨论】:

  • 试试这个:test1&lt;- df[!df$location %in% c('newyork','delhi'), ]
  • 谢谢!成功了!

标签: r dataframe dplyr subset


【解决方案1】:

正如@ycw 在评论中指出的那样,否定逻辑条件会给你预期的结果

location <- c('london', 'london','london', 'newyork' ,'newyork', 'paris', 'delhi')
year <- c(1990, 1991, 1992, 2001, 2002, 2003,2001)

df <- data.frame(location, year)

x <- c('newyork', 'delhi')

# add"!" to the subset condition
test1 <- df[ !df$location %in% c('newyork','delhi'), ] 

test1

结果

  location year
1   london 1990
2   london 1991
3   london 1992
6    paris 2003

【讨论】:

    【解决方案2】:

    使用 Dplyr:

    new_df <- df %>% 
      filter(!(location %in% c("newyork", "delhi")))
    

    【讨论】:

      【解决方案3】:

      如果您只想从原始数据框中排除几个元素,您还可以按如下方式创建子集:

      location <- c('london', 'london','london', 'newyork' ,'newyork', 
      'paris', 'delhi')
      year<- c(1990, 1991, 1992, 2001, 2002, 2003,2001)
      
      df<- data.frame(location,year)
      
      # Identify which elements you wish to remove and precede with NOT operator (!)
      df2 <- df[!df$location=="newyork" & !df$location=="paris",]
      
      df2
      

      请注意,如果您打算过滤多个元素,这不是很有效。在这些情况下,ycw 和 Damian 的方法更好。

      但是,如果您只有一个或几个元素要删除,那么上述安排是一种简单、快速、合乎逻辑的方法来实现您所追求的目标:

       location year
      1   london 1990
      2   london 1991
      3   london 1992
      7    delhi 2001
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        相关资源
        最近更新 更多