首页 > 解决方案 > 如何使用 dplyr 中的 select 函数返回结果?

问题描述

我的数据在表格(我称之为表格)中看起来像这样:

第 1 列:(苹果 A、苹果 B、香蕉 A、香蕉 B)

第 2 列:(1、2、3、4)

我想创建一个以 A 结尾的所有第 1 列和所有以 B 结尾的第 1 列的向量。我正在使用:A<-select(table, ends_with("A")),试图获得“Apples A”Apples B“的值。相反,我得到一个具有 4 个观察值和 0 个变量的数据框。我确实尝试A<-grepl("A", fixed=TRUE, table$column1)过,但这给了我真、假、真、假,这不是我想要的。我可能遗漏了一些愚蠢明显的东西,不是吗?

标签: r

解决方案


使用 stringr 处理字符串:

$ 表示以结尾,^ 表示以开头

library(stringr)

df %>% filter(str_detect(column_1, "A$"))
  column_1 column_2
1  Apples A        1
2 Bananas A        3

# or :

> df %>% filter(str_detect(column_1, "^Bananas"))
   column_1 column_2
1 Bananas A        3
2 Bananas B        4

# or use both at the same time:

> df %>% filter(str_detect(column_1, "^Bananas A$")) 
   column_1 column_2
1 Bananas A        3

############ then use select to only select the first column: column_1  

df %>% filter(str_detect(column_1, "A$")) %>%  select(column_1)

# same as:
df %>% filter(str_detect(1, "A$")) %>%  select(1)

########### Finally to store it in a vector "myvector" you can use pull()

df %>% filter(str_detect(1, "A$")) %>%  select(1) %>% pull(1) -> myvector


推荐阅读