1

I can use stringr to find the start "http" location at first row,

library(stringr)

a <- str_locate(message[1,], "http")[1]
a 
[1] 38

I want to find the start location for each row, and use "apply" fuction:

message$location <- apply(message, 1, function(x) str_locate(message[x,], "http")[1]) 

But it shows all "NA" values, could I fix it?

Jeffery Chen
  • 323
  • 2
  • 4
  • 13

1 Answers1

1

As we are using anonymous function call (function(x)), we can use the input variable for each row as x i.e. str_locate(x, ...)

apply(message, 1, function(x) str_locate(x, "http")[1])
#[1] 11 16

Or without specifying the anonymous function

apply(message, 1, str_locate, pattern="http")[1,]
#[1] 11 16

As @thelatemail mentioned, if we are only looking for patterns in the first column, we don't need an apply loop.

str_locate(message[,1], "http")[,1]
#[1] 11 16

data

message <- data.frame(V1= c("Something http://www...", 
            "Something else http://www.."), v2= 1:2)
akrun
  • 874,273
  • 37
  • 540
  • 662