繁体   English   中英

R:字符串查找行的起始位置

[英]R: stringr to find the start location for rows

我可以使用stringr在第一行找到开始的“ http”位置,

library(stringr)

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

我想找到每行的开始位置,并使用“应用”功能:

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

但是它显示所有“ NA”值,我可以解决它吗?

当我们使用匿名函数调用( function(x) )时,我们可以将每行的输入变量用作xstr_locate(x, ...)

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

或不指定匿名功能

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

作为@thelatemail提到的,如果我们只是在第一列寻找模式,我们并不需要一个apply循环。

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

数据

message <- data.frame(V1= c("Something http://www...", 
            "Something else http://www.."), v2= 1:2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM