簡體   English   中英

R dplyr:刪除多列

[英]R dplyr: Drop multiple columns

我有一個數據框和該數據框中的列列表,我想刪除它。 我們以iris數據集為例。 我想刪除Sepal.LengthSepal.Width並僅使用剩余的列。 如何使用dplyr包中的selectselect_執行此操作?

這是我迄今為止嘗試過的:

drop.cols <- c('Sepal.Length', 'Sepal.Width')
iris %>% select(-drop.cols)

-drop.cols 中的錯誤:一元運算符的參數無效

iris %>% select_(.dots = -drop.cols)

-drop.cols 中的錯誤:一元運算符的參數無效

iris %>% select(!drop.cols)

!drop.cols 中的錯誤:無效的參數類型

iris %>% select_(.dots = !drop.cols)

!drop.cols 中的錯誤:無效的參數類型

我覺得我錯過了一些明顯的東西,因為這些似乎是一個應該已經存在的非常有用的操作。 在 Github 上,有人發布了一個類似的問題,Hadley 說要使用“負索引”。 這就是(我認為)我嘗試過的,但無濟於事。 有什么建議么?

檢查有關 select_vars 的幫助。 這為您提供了一些關於如何使用它的額外想法。

在你的情況下:

iris %>% select(-one_of(drop.cols))

也試試

## Notice the lack of quotes
iris %>% select (-c(Sepal.Length, Sepal.Width))

除了select(-one_of(drop.cols))還有一些其他選項可以使用select()刪除列,這些選項不涉及定義所有特定列名(使用 dplyr starwars 示例數據以獲得更多種類的列名):

starwars %>% 
  select(-(name:mass)) %>%        # the range of columns from 'name' to 'mass'
  select(-contains('color')) %>%  # any column name that contains 'color'
  select(-starts_with('bi')) %>%  # any column name that starts with 'bi'
  select(-ends_with('er')) %>%    # any column name that ends with 'er'
  select(-matches('^f.+s$')) %>%  # any column name matching the regex pattern
  select_if(~!is.list(.)) %>%     # not by column name but by data type
  head(2)

# A tibble: 2 x 2
homeworld species
  <chr>     <chr>  
1 Tatooine  Human  
2 Tatooine  Droid 

小心select()函數,因為它在 dplyr 和 MASS 包中都使用,所以如果加載了 MASS,select() 可能無法正常工作。 要找出加載了哪些包,請鍵入sessionInfo()並在“其他附加包:”部分中查找。 如果已加載,請鍵入detach( "package:MASS", unload = TRUE ) ,您的select()函數應該會再次運行。

我們能試試

iris %>% 
      select_(.dots= setdiff(names(.),drop.cols))

如果列名稱中有特殊字符,則selectselect_可能無法按預期工作。 使用"."dplyr的這個屬性"." . 要參考問題中的數據集,可以使用以下行來解決此問題:

drop.cols <- c('Sepal.Length', 'Sepal.Width')
  iris %>% .[,setdiff(names(.),drop.cols)]

另一種方法是將不需要的列更改為NULL ,這樣可以避免嵌入括號:

head(iris,2) %>% mutate_at(drop.cols, ~NULL)
#   Petal.Length Petal.Width Species
# 1          1.4         0.2  setosa
# 2          1.4         0.2  setosa

我也遇到了同樣的問題,但主要錯誤在於包含具有與“select()”同名的另一個函數定義的庫。 對我來說,它與 MASS 包選擇功能發生沖突。

分離 MASS 庫后,錯誤停止。

你可以試試

iris %>% select(-!!drop.cols)

對於任何到達這里想要刪除一系列列的人。

最小的可重復示例

刪除一系列列,如下所示:

iris %>% 
  select(-(Sepal.Width:Petal.Width)) %>% 
  head

#   Sepal.Length Species
# 1          5.1  setosa
# 2          4.9  setosa
# 3          4.7  setosa
# 4          4.6  setosa
# 5          5.0  setosa
# 6          5.4  setosa

筆記:

  • 列名周圍的( , )很重要,必須使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM