啊啊啊啊啊吖

2018-11-03   阅读量: 772

数据分析师 R语言

使用select()选择列

扫码加入数据分析学习群

如今,数据集有几百甚至几千个变量已经司空见惯。这种情况下,如何找出真正感兴趣的

那些变量经常是我们面临的第一个挑战。通过基于变量名的操作, select() 函数可以让你

快速生成一个有用的变量子集。

select() 函数对于航班数据不是特别有用,因为其中只有 19 个变量,但你还是可以通过

这个数据集了解一下 select() 函数的大致用法:

# 按名称选择列
select(flights, year, month, day)
#> # A tibble: 336,776 × 3
#> year month day
#> <int> <int> <int>
#> 1 2013 1 1
#> 2 2013 1 1
#> 3 2013 1 1
#> 4 2013 1 1
#> 5 2013 1 1
#> 6 2013 1 1
#> # ... with 3.368e+05 more rows

# 选择“year”和“day”之间的所有列(包括“year”和“day”)
select(flights, year:day)
#> # A tibble: 336,776 × 3
#> year month day
#> <int> <int> <int>
#> 1 2013 1 1
#> 2 2013 1 1
#> 3 2013 1 1
#> 4 2013 1 1
#> 5 2013 1 1
#> 6 2013 1 1
#> # ... with 3.368e+05 more rows

# 选择不在“year”和“day”之间的所有列(不包括“year”和“day”)
select(flights, -(year:day))
#> dep_time sched_dep_time dep_delay arr_time sched_arr_time
#> <int> <int> <dbl> <int> <int>
#> 1 517 515 2 830 819
#> 2 533 529 4 850 830
#> 3 542 540 2 923 850
#> 4 544 545 -1 1004 1022
#> 5 554 600 -6 812 837
#> 6 554 558 -4 740 728
#> # ... with 3.368e+05 more rows, and 12 more variables:
#> # arr_delay <dbl>, carrier <chr>, flight <int>,
#> # tailnum <chr>, origin <chr>, dest <chr>, air_time <dbl>,
#> # distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>

还可以在 select () 函数中使用一些辅助函数。

• starts_with("abc"):匹配以“abc”开头的名称。

• ends_with("xyz"):匹配以“xyz”结尾的名称。

• contains("ijk"):匹配包含“ijk”的名称。

• matches("(.)\\1"):选择匹配正则表达式的那些变量。这个正则表达式会匹配名称中有

重复字符的变量。

• num_range("x", 1:3):匹配 x1、 x2 和 x3。

使用 ?select 命令可以获取更多信息。

select() 可以重命名变量,但我们很少这样使用它,因为这样会丢掉所有未明确提及的变

量。我们应该使用 select() 函数的变体 rename() 函数来重命名变量,以保留所有未明确

提及的变量:

rename(flights, tail_num = tailnum)
#> # A tibble: 336,776 × 19
#> year month day dep_time sched_dep_time dep_delay
#> <int> <int> <int> <int> <int> <dbl>
#> 1 2013 1 1 517 515 2
#> 2 2013 1 1 533 529 4
#> 3 2013 1 1 542 540 2
#> 4 2013 1 1 544 545 -1
#> 5 2013 1 1 554 600 -6
#> 6 2013 1 1 554 558 -4
#> # ... with 3.368e+05 more rows, and 13 more variables:
#> # arr_time <int>, sched_arr_time <int>, arr_delay <dbl>,
#> # carrier <chr>, flight <int>, tail_num <chr>,
#> # origin <chr>, dest <chr>, air_time <dbl>,
#> # distance <dbl>, hour <dbl>, minute <dbl>,
#> # time_hour <dttm>

另一种用法是将 select() 函数和 everything() 辅助函数结合起来使用。当想要将几个变

量移到数据框开头时,这种用法非常奏效:

select(flights, time_hour, air_time, everything())
#> # A tibble: 336,776 × 19
#> time_hour air_time year month day dep_time
#> <dttm> <dbl> <int> <int> <int> <int>

#> # A tibble: 336,776 × 16

添加CDA认证专家【维克多阿涛】,微信号:【cdashijiazhuang】,提供数据分析指导及CDA考试秘籍。已助千人通过CDA数字化人才认证。欢迎交流,共同成长!
0.0000 0 3 关注作者 收藏

评论(0)


暂无数据

推荐课程

推荐帖子