Skip to content
Prev 383923 / 398502 Next

how to extract strings in any column and in any row that start with

This is almost certainly not the most efficient way:

tot <- data.frame(v1 = paste0(LETTERS[seq(1:5)],seq(1:10)),
              v2 = paste0(LETTERS[seq(1:5)],seq(from = 101, to=110, by = 
1)),
              v3 = paste0(LETTERS[seq(1:5)],seq(from = 111, to=120, by = 
1)),
              v4 = paste0(LETTERS[seq(1:5)],seq(from = 121, to=130, by = 
1)),
              v5 = paste0(LETTERS[seq(1:5)],seq(from = 131, to=140, by = 
1)),
              v6 = paste0(LETTERS[seq(1:5)],seq(from = 101, to=110, by = 
1))
              )

# set a variable to hold the result
myResult <- NULL

# iterate through each variable
for (v in 1:length(tot[1,])) {
   thisResult <- as.character(tot[grepl ('^E10', tot[,v]),v])
   myResult <- c(myResult, thisResult)
}

myResult <- unique( myResult )


===

Indeed as I wrote this Jeff has popped along with unlist!

Using my example above:

unique ( as.character( unlist (tot) )[grepl ('^E10', as.character( 
unlist (tot) ) )] )

does what you wanted (you may not need the as.characters if you are on R 
4.o, or if your df has chars rather than factors.
On 2020-05-15 21:34, Jeff Newmiller wrote: