在“/”之后提取文本在R编程中的数据帧中 [英] Extract text after "/" in a data frame in R Programming
问题描述
我有一个数据框,其中有两列链接和值。 链接列的值为abcd.com/efgh/ijkl/mnop,是一个URL。在这个框架中有10,000行,我从100,000行的样本中获取。
I have a data frame that has two columns Link and Value. The Link column has values like "abcd.com/efgh/ijkl/mnop" and is a URL. There are 10,000 rows in this frame which i have taken from a sample of 100,000 rows.
现在我要从左到右提取最后一个/之后的数据或从右到左的第一个/。所以例如在上面的示例中,我提取mnop
Now I want to extract the data after the last "/" from left to right or first "/" from right to left. So for eg in the above sample shown I was to extract "mnop"
我想为列中的所有10,000行执行此操作链接,而价值栏不应该有效。
I want to do this for all the 10,000 rows that is there in the column Link while the Value column should not be effected.
我可以使用
a = sapply(webdatatest, substring, 36)
但是这不是一个动态的方法,因为最后一个/的位置会改变。这也是第二列。
but this is not a dynamic method as positions of last "/" would change.Also this was effecting the second column also.
所以需要一些帮助
推荐答案
尝试 basename()
。
删除最后一个路径分隔符(如果有)的所有路径。
removes all of the path up to and including the last path separator (if any).
basename("abcd.com/efgh/ijkl/mnop")
# [1] "mnop"
它是矢量化的,所以你可以把整个列放在那里。
It is vectorized, so you can just stick the whole column in there.
basename(rep("abcd.com/efgh/ijkl/mnop", 3))
# [1] "mnop" "mnop" "mnop"
所以,将其应用于一列链接
数据框 webdata
,您可以简单地执行
So, to apply this to one column link
of a data frame webdata
, you can simply do
webdata$link <- basename(webdata$link)
另一个明显的功能是 sub()
,但我认为 basename()
会做的伎俩,它更容易。
The other obvious function would be sub()
, but I think basename()
will do the trick and it's easier.
sub(".*/", "", rep("abcd.com/efgh/ijkl/mnop", 3))
这篇关于在“/”之后提取文本在R编程中的数据帧中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!