简体   繁体   English

如何使用R从一列的字符串中提取特定数字并将其存储在数据框的另一列中?

[英]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.

相关问题 如何基于R中另一列的值从数据框中的一列提取值 - How to extract values from one column in a data frame based on values in another in R R:根据另一列中检测到的字符串从一列中提取数据 - R: extract data from one column based on string detected in another R:从一个数据框中提取行,基于列名匹配另一个数据框中的值 - R: Extract Rows from One Data Frame, Based on Column Names Matching Values from Another Data Frame R根据其参考列将特定列从一个数据帧合并到另一数据帧 - R merge a particular column from one data frame to another according to its reference column 使用列作为列索引从 R 中的数据框中提取值 - Using a column as a column index to extract value from a data frame in R 在第一个逗号之后提取字符串,并使用R将其存储在另一列中 - Extract string after first comma and store it in another column using R 从列中提取模式并在 R 数据框中创建一个新模式 - Extract a pattern from column and make a new one in R data frame 根据数据框R中的另一列从另一列中提取一列的值 - Extract values for a column from another column based on another column in data frame R 如何从 R 中的另一个 Dataframe 添加新列,对应于第一个数据帧中的特定样本 - How to add New Column from another Dataframe in R corresponding to the particular samples in First Data frame 将数据从一个数据框的列导入到R中的另一数据框? - Importing data from column of one data frame to another dataframe in r?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM