Reputation: 135
Hi I have a vector of string in R which are separated by @ , I want to extract words separated by @..Example
tweets =c( " @john @tom it is wonderful ", "@neel it is awesome ", "it is awesome")
I want a matrix/data.frame of names only with no text like this as output
X1=c("john","tom')
X2 =c("neel",NA) , x3 = (NA,NA), data frame = as.data.frame(X1,X2,x3)
How can I do it?
Upvotes: 1
Views: 131
Reputation: 887028
A base R
option would be to extract using gregexpr/regmatches
and then pad NA
s to the list
elements with length<-
and convert to a matrix
lst <- regmatches(tweets, gregexpr("(?<=@)\\w+", tweets, perl = TRUE))
do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
# [,1] [,2]
#[1,] "john" "tom"
#[2,] "neel" NA
#[3,] NA NA
Upvotes: 2