Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/jsp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
str_extract_all返回一个列表,但我需要一个向量_R_Stringr - Fatal编程技术网

str_extract_all返回一个列表,但我需要一个向量

str_extract_all返回一个列表,但我需要一个向量,r,stringr,R,Stringr,在这里对R还是比较新的。我有一列tweets,我正在尝试创建一个包含转发句柄“RT@blahblah”的列,如下所示: Tweets Retweetfrom RT @john I had a good day RT @john RT @josh I had a bad day RT @josh 这是我的代码: r$Retweetfrom <- str_extract_all(r$Tweets, "^R

在这里对R还是比较新的。我有一列tweets,我正在尝试创建一个包含转发句柄“RT@blahblah”的列,如下所示:

Tweets                            Retweetfrom
RT @john I had a good day         RT @john
RT @josh I had a bad day          RT @josh
这是我的代码:

r$Retweetfrom <- str_extract_all(r$Tweets, "^RT[:space:]+@[:graph:]+")

r$Retweetfrom假设
Tweets
列的每一行中只有一个RT@user(这不是一个很强的假设),那么您可能只需要
stru-extract
(它将矢量化字符串),而不是
stru-extract\u-all
(每行可能返回多个结果)。i、 e


r$Retweetfrom如果我们对
base r
选项感兴趣,
sub
将非常有用

r$Retweetfrom <- sub(".*\\b(RT\\s+@[[:graph:]]+)\\s+.*", 
                         "\\1", r$Tweets)
r$Retweetfrom
#[1] "RT @john" "RT @josh"

r$Retweetfrom Ahh,这很有道理,谢谢!但是如果我试图提取推文中提到的所有内容呢?有时一条推文中会有不止一次的提及,这是一个稍微不同的问题;此时,您的正则表达式捕获了在正则表达式中使用
^
的人(我第一次错过了它),因此您最多只能得到一个(我的坏消息再次出现,错过了
+
;您将获得全部)。如果您想捕获tweet中提到的所有
@user
,无论他们是否进行了RT,那么您需要决定如何在
data.frame
中存储可变大小的列表。这现在就更有意义了。非常感谢你,乔纳森!可以肯定的是,您只需执行“simplify=T”,它就会将结果转换为可变大小的矩阵。
r$Retweetfrom <- str_extract(r$Tweets, "^RT[:space:]+@[:graph:]+")
r$Retweetfrom <- sub(".*\\b(RT\\s+@[[:graph:]]+)\\s+.*", 
                         "\\1", r$Tweets)
r$Retweetfrom
#[1] "RT @john" "RT @josh"