0

My data looks like this in a table (which I've called table):

column 1: (Apples A, Apples B, Bananas A, Bananas B)

column 2: (1, 2, 3, 4)

I want to create a vector of all the column 1 ending in A, and all the column 1 ending in B. I'm using: A<-select(table, ends_with("A")), in an attempt to get a value of "Apples A "Apples B". Instead, I get a data frame with 4 observations and 0 variables. I did try A<-grepl("A", fixed=TRUE, table$column1) but that gave me true, false, true, false, which isn't what I want. I'm probably missing something stupidly obvious aren't I?

  • Have you tried `?dplyr::filter` ? – markus Apr 05 '20 at 18:40
  • Welcome to Stack Overflow! Could you make your problem reproducible by sharing a sample of your data so others can help (please do not use `str()`, `head()` or screenshot)? You can use the [`reprex`](https://reprex.tidyverse.org/articles/articles/magic-reprex.html) and [`datapasta`](https://cran.r-project.org/web/packages/datapasta/vignettes/how-to-datapasta.html) packages to assist you with that. See also [Help me Help you](https://speakerdeck.com/jennybc/reprex-help-me-help-you?slide=5) & [How to make a great R reproducible example?](https://stackoverflow.com/q/5963269) – Tung Apr 05 '20 at 18:47
  • @markus Error: No tidyselect variables were registered is the error message I get using filter. I tried doing ```tabled – codingnewbie Apr 05 '20 at 19:03

1 Answers1

1

Use stringr to work with strings:

$ means ends with, ^ means starts with

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

user12256545
  • 1,479
  • 6
  • 22