R: sub() 使用向量作为模式
假设我有一个如下所示的数据框:
df=data.frame(a=LETTERS, b=paste0(LETTERS,1:length(LETTERS)))
它看起来像这样:
> df
a b
1 A A1
2 B B2
3 C C3
4 D D4
5 E E5
6 F F6
7 G G7
8 H H8
9 I I9
10 J J10
11 K K11
12 L L12
...
我唯一想做的就是从 df$b
中删除 df$a
,以便得到结果数据框看起来像:
> df
a b
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F 6
7 G 7
8 H 8
9 I 9
10 J 10
11 K 11
12 L 12
...
为此,我想显式使用 sub()
和 df$a
作为模式。此数据框只是一个示例,因此我不想在 sub()
中使用 strsplit()
或特定正则表达式(因为我的 df$a< /code> 可能会变得相当复杂)。
我尝试:
df$b=sub(paste0("^",df$a) , "", df$b)
但显然我得到:
警告消息:在 sub(paste0("^", df$a), "", df$b) 中:参数 “模式”的长度> 1 并且仅使用第一个元素
那么正确的方法是什么?谢谢!
Say I have a data frame like the following:
df=data.frame(a=LETTERS, b=paste0(LETTERS,1:length(LETTERS)))
It looks like this:
> df
a b
1 A A1
2 B B2
3 C C3
4 D D4
5 E E5
6 F F6
7 G G7
8 H H8
9 I I9
10 J J10
11 K K11
12 L L12
...
The only thing I want to do is remove df$a
from df$b
, so that the resulting data frame looks like:
> df
a b
1 A 1
2 B 2
3 C 3
4 D 4
5 E 5
6 F 6
7 G 7
8 H 8
9 I 9
10 J 10
11 K 11
12 L 12
...
For that, I want to explicitly use sub()
with df$a
as pattern. This data frame is just an example, so I do not want to use strsplit()
or a specific regex in sub()
(cause my df$a
can get pretty complicated).
I try:
df$b=sub(paste0("^",df$a) , "", df$b)
But obviously I get:
Warning message: In sub(paste0("^", df$a), "", df$b) : argument
'pattern' has length > 1 and only the first element will be used
So what would be the right way to do this? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用
mapply
从df$b
中删除df1$a
。由 reprex 软件包 (v2.0.1) 于 2022 年 3 月 16 日创建
分配回
df$b
,保留为字符,运行由 reprex 包 (v2.0.1)
Use
mapply
to removedf1$a
fromdf$b
.Created on 2022-03-16 by the reprex package (v2.0.1)
To assign back to
df$b
, keeping as characters, runCreated on 2022-03-16 by the reprex package (v2.0.1)