Home > database >  Dropping a value from a character vector based on an index value in R
Dropping a value from a character vector based on an index value in R

Time:04-28

I have a character vector that I need to drop a specific one from it based on an index value. Here is a sample:

index <- as.integer(2)

object <- c("(G1, 70, Slope[1]) = 0.0;" , "(G1, 70, Slope[2]) = 0.0;",  "(G1, 70, Slope[3]) = 0.0;")

    > object
[1] "(G1, 70, Slope[1]) = 0.0;" "(G1, 70, Slope[2]) = 0.0;" "(G1, 70, Slope[3]) = 0.0;"

The index value is 2 so I need to drop the second value Slope[index] which has 2 inside of the Slope[2].

The desired output would be :

> object2
[1] "(G1, 70, Slope[1]) = 0.0;" "(G1, 70, Slope[3]) = 0.0;"

Any ideas on this?

Thanks

CodePudding user response:

You can also use extract from magrittr:

magrittr::extract(object, -index)

# [1] "(G1, 70, Slope[1]) = 0.0;" "(G1, 70, Slope[3]) = 0.0;"

Or the easiest is given by @akrun with basic subsetting:

object[-index]

CodePudding user response:

Or use grep to find the object(s) that you want to delete.

pattern = paste(c("[", index, "]"), collapse="")
object = object[-grep(pattern, object)]
object
[1] "(G1, 70, Slope[1]) = 0.0;" "(G1, 70, Slope[3]) = 0.0;"
  • Related