你可以在dplyr中使用以下基本语法,通过索引位置选择数据框架的列:
#select columns in specific index positions
df %>%
select(1, 4, 5)
#exclude columns in specific index positions
df %>%
select(-c(1,2))
下面的例子展示了如何在以下数据框架中实际使用这种语法:
#create data frame
df <- data.frame(team=c('A', 'B', 'C', 'D', 'E'),
points=c(99, 90, 86, 88, 95),
assists=c(33, 28, 31, 39, 34),
rebounds=c(30, 28, 24, 24, 28),
blocks=c(14, 19, 22, 18, 15))
#view data frame
df
team points assists rebounds blocks
1 A 99 33 30 14
2 B 90 28 28 19
3 C 86 31 24 22
4 D 88 39 24 18
5 E 95 34 28 15
例1:选择特定索引位置的列
下面的代码展示了如何在特定的索引位置上选择列:
library(dplyr)
#select columns in position 1, 4, and 5
df %>%
select(1, 4, 5)
team rebounds blocks
1 A 30 14
2 B 28 19
3 C 24 22
4 D 24 18
5 E 28 15
例2:选择范围内的列
下面的代码显示了如何在一个范围内选择列:
library(dplyr)
#select columns in position 2 through 4
df %>%
select(2:4)
points assists rebounds
1 99 33 30
2 90 28 28
3 86 31 24
4 88 39 24
5 95 34 28
例3:排除特定的列
下面的代码显示了如何根据索引位置排除特定的列:
library(dplyr)
#select all columns except those in position 1 and 2
df %>%
select(-c(1, 2))
assists rebounds blocks
1 33 30 14
2 28 28 19
3 31 24 22
4 39 24 18
5 34 28 15
注意,第一和第二列被排除了。
其他资源
下面的教程解释了如何在dplyr中执行其他常用功能: