R 使用长度大于 1 的模式替换为 gsub
R replacing with gsub using a pattern with a length greater than 1
我有一个 data.frame example
和一个变量 (care_group
) 如下:
> example
care_group
1 1st Choice Care Homes 8.8
2 2Care
3 229 Mitcham Lane Ltd
4 3 L Care Ltd
5 3AB Care Ltd
6 9Grace Road Ltd
7 A&R Care Ltd 9.7
8 ABLE (Action for a Better Life)
9 A C L Care Homes Ltd
10 A D L plc
11 A D R Care Homes Ltd
12 A G E Nursing Homes Ltd 8
您可能会注意到,我的一些观察结果是字母数字的,并且在开头 and/or 和结尾名称中都包含数字。我知道可以去掉数字字符(例如 here)。然而,我不知道如何只删除其中的一些。具体来说,删除名称末尾的数字并保留开头的数字。我试图通过创建一个包含我要删除的数字的组并尝试使用 gsub
来做到这一点。
ratings = c("8", "8.8", "9.7")
example$new_var = with(example, gsub(ratings, " ", care_group))
但是我收到此警告消息:
Warning message:
In gsub(ratings, " ", care_group) :
argument 'pattern' has length > 1 and only the first element will be used
我想知道是否可以将 gsub 与长度 > 1 的模式一起使用,或者是否有人可以提出更有效的方法来解决这个问题。提前谢谢了。
最好使用锚点和字符class:
# sample of vector with various possibilities
temp <- c(" 7 A&R Care Ltd 9.7", "A C L Care Homes Ltd", "12 A G E Nursing Homes Ltd 8")
gsub(" [0-9.]+$", "", temp)
[1] " 7 A&R Care Ltd" "A C L Care Homes Ltd" "12 A G E Nursing Homes Ltd"
在正则表达式中
$
将表达式锚定到文本末尾
- “[0-9.]+”表示任何数字字符序列,包括“.”
我有一个 data.frame example
和一个变量 (care_group
) 如下:
> example
care_group
1 1st Choice Care Homes 8.8
2 2Care
3 229 Mitcham Lane Ltd
4 3 L Care Ltd
5 3AB Care Ltd
6 9Grace Road Ltd
7 A&R Care Ltd 9.7
8 ABLE (Action for a Better Life)
9 A C L Care Homes Ltd
10 A D L plc
11 A D R Care Homes Ltd
12 A G E Nursing Homes Ltd 8
您可能会注意到,我的一些观察结果是字母数字的,并且在开头 and/or 和结尾名称中都包含数字。我知道可以去掉数字字符(例如 here)。然而,我不知道如何只删除其中的一些。具体来说,删除名称末尾的数字并保留开头的数字。我试图通过创建一个包含我要删除的数字的组并尝试使用 gsub
来做到这一点。
ratings = c("8", "8.8", "9.7")
example$new_var = with(example, gsub(ratings, " ", care_group))
但是我收到此警告消息:
Warning message:
In gsub(ratings, " ", care_group) :
argument 'pattern' has length > 1 and only the first element will be used
我想知道是否可以将 gsub 与长度 > 1 的模式一起使用,或者是否有人可以提出更有效的方法来解决这个问题。提前谢谢了。
最好使用锚点和字符class:
# sample of vector with various possibilities
temp <- c(" 7 A&R Care Ltd 9.7", "A C L Care Homes Ltd", "12 A G E Nursing Homes Ltd 8")
gsub(" [0-9.]+$", "", temp)
[1] " 7 A&R Care Ltd" "A C L Care Homes Ltd" "12 A G E Nursing Homes Ltd"
在正则表达式中
$
将表达式锚定到文本末尾- “[0-9.]+”表示任何数字字符序列,包括“.”