-1

I have a character vector which looks like this:

chars <- c("Classics football boots", "Classics football shoes","football shoes", "new footbal shoes")

In this chars object i want to select only elements football shoes & football boots. With maintaining the order because i need to replace the vector back into a dataframe.

If tried many things but i think this comes most close:

for (i in grep("Classics",chars)){
  temp <- as.character(strsplit(chars[i], " ")[[1]][c(2,3)])
  temp2 <- as.character(na.omit(temp))
  chars[i] <- temp2
}

How can i get the object like this:

c("football boots", "football shoes","football shoes", "new footbal shoes")

So i only want to touch the values containing classics (or whatever word of interest).

Update:

Since I see that the question is not clear I will try to elaborate a bit more:

The vector that I have contains 4000 plus values. So I want to select values from the vector based on some string (in this example "Classics"). Then if I find that word I want to be able to select only parts of that string that are needed. In this example I want to select the second and third element of that value. Hope its more clear now.

Sander Van der Zeeuw
  • 1,092
  • 1
  • 13
  • 35

2 Answers2

1

One idea using grepl and word from stringr,

chars[grepl('Classics', chars)] <- stringr::word(chars[grepl('Classics', chars)], 2, 3)
chars
#[1] "football boots"    "football shoes"    "football shoes"    "new footbal shoes"
Sotos
  • 51,121
  • 6
  • 32
  • 66
0

Why not simply this:

gsub("Classics\\s+", "", chars)
# [1] "football boots"    "football shoes"    "football shoes"    "new footbal shoes"
Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63