我有一个数据框和该数据框中的列列表,我想放弃.我们以iris数据集为例.我想放弃Sepal.Length并Sepal.Width仅使用其余列.如何使用select或select_从dplyr包中执行此操作?
这是我到目前为止所尝试的:
drop.cols <- c('Sepal.Length', 'Sepal.Width')
iris %>% select(-drop.cols)
Run Code Online (Sandbox Code Playgroud)
-drop.cols中的错误:一元运算符的参数无效
iris %>% select_(.dots = -drop.cols)
Run Code Online (Sandbox Code Playgroud)
-drop.cols中的错误:一元运算符的参数无效
iris %>% select(!drop.cols)
Run Code Online (Sandbox Code Playgroud)
!drop.cols出错:参数类型无效
iris %>% select_(.dots = !drop.cols)
Run Code Online (Sandbox Code Playgroud)
!drop.cols出错:参数类型无效
我觉得我错过了一些明显的东西,因为这些似乎是一个非常有用的操作,应该已经存在.在Github上,有人发布了类似的问题,Hadley说要使用"负索引".这就是(我认为)我尝试过的,但无济于事.有什么建议?
phi*_*ver 110
查看select_vars上的帮助.这为您提供了一些关于如何使用它的额外想法.
在你的情况下:
iris %>% select(-one_of(drop.cols))
Run Code Online (Sandbox Code Playgroud)
Mig*_*lez 53
也试试
## Notice the lack of quotes
iris %>% select (-c(Sepal.Length, Sepal.Width))
Run Code Online (Sandbox Code Playgroud)
sbh*_*bha 24
除此之外,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
Run Code Online (Sandbox Code Playgroud)
小智 6
注意这个select()函数,因为它在dplyr和MASS包中都使用过,所以如果加载了MASS,select()可能无法正常工作.要找出加载了哪些包sessionInfo(),请在"其他附加包:"部分中键入并查找它.如果已加载,请键入detach( "package:MASS", unload = TRUE ),您的select()功能应该再次起作用.
对于任何到达这里想要删除一系列列的人。
删除一系列列,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
笔记:
(使用)我们可以尝试
iris %>%
select_(.dots= setdiff(names(.),drop.cols))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
92339 次 |
| 最近记录: |