[R] how to get all strings in a data frame that start with a particular string

Rasmus Liland jen@r@@mu@ @end|ng |rom gm@||@com
Fri Apr 10 19:00:48 CEST 2020


On 2020-04-10 11:15 -0500, Ana Marija wrote:
> I have a data frame (tot) with about 
> 2000 columns. How can I extract from 
> it all strings that start with E14?
> 
> I tried this:
> e14 <- sapply(tot, function(x) grepl("^E14", x))
> 
> but this returns me just TRUE and 
> FALSE vector, how do I get actual 
> strings that start with E14?

Dear Ana,

perhaps you thought of something along 
the lines of this:

  ncol <- 2000
  nrow <- 3
  line <-
    c("a", "b",
      "some text E14 bla bla some more text",
      "d",
      "E14 ... hey this starts and also ends with E14",
      "E14 something-something",
      "another string")
  tot <-
    as.data.frame(matrix(rep(line,
      times=ncol*nrow),
      ncol=ncol,
      byrow=T))
  
  # Now, tot is a df with some cells
  # containing replicates of line, some
  # cells there are now starting with E14
  # ... so we need to convert it to a
  # character matrix to be able to find
  # the indecies of the cells starting
  # with E14:
  
  tot <- as.matrix(tot)
  idx <- grepl("^E14", tot)
  tot[idx]

Best,
Rasmus



More information about the R-help mailing list