[英]How to extract a particular number from a string of one column and store it in another column of data frame using R?
I have a data frame which look like: Check The Data frame Here我有一个数据框,它看起来像:在这里检查数据框
I am facing an issue while extracting the value of ID from cs.uri.query column and storing that particular value in another column in same data frame.我在从 cs.uri.query 列中提取 ID 的值并将该特定值存储在同一数据框中的另一列中时遇到问题。 I tried a lot of methods like regex grep but still not able to solve.
我尝试了很多方法,如regex grep,但仍然无法解决。 Basically what result i want to get would something be like: Result
基本上我想要得到的结果是这样的:结果
Need help solve this issue.Thanks In Advance.需要帮助解决这个问题。提前致谢。
You could use the str_match
function of the stringr
library:您可以使用
str_match
的功能stringr
库:
library(stringr) df$UserId <- str_match(df$cs.uri.query, "ID=([0-9]+)")[,2]
This will search for any matches to ID=<some number>
and return the first bracketed match, ie the number.这将搜索
ID=<some number>
任何匹配项并返回第一个括号匹配项,即数字。
Using gsub
in base R...在基础 R 中使用
gsub
...
df$UserID <- gsub(".*ID=([0-9]+).*","\\1",df$cs.uri.query)
This captures (in ()
) the string of digits after ID=
, and replaces the whole string (hence the .*
at either side, which means any characters) with the first (and only) captured group \\\\1
.这将捕获(在
()
) ID=
之后的数字字符串,并用第一个(也是唯一一个)捕获的组\\\\1
替换整个字符串(因此在任何一侧都有.*
,这意味着任何字符)。
I've not been able to test it on your data, but it should work.我无法在您的数据上对其进行测试,但它应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.