问题描述
我有一个像这样的数据框:
I have a data frame like this:
name weight
r apple 0.5
y pear 0.4
y cherry 0.1
g watermelon 5.0
pp grape 0.5
y apple pear 0.4
... ...
我想删除名称列中第一个空格之前的所有字符.有人可以帮我一个忙吗?谢谢!
I would like to remove all characters before the first white space in the name column. Can anybody give me a favor? Thank you!
推荐答案
尝试一下:
sub(".*? ", "", D$name)
此模式正在寻找零个或多次(.*
)直到第一个空格的字符,然后捕获该第一个空格之后的一个或多个字符((.+)
). .*
之后的?
使它成为懒惰"而不是贪婪",这就是它在找到的第一个空格处停止的原因.因此,.*?
匹配第一个空格之前的所有内容,该空格匹配找到的第一个空格.
The pattern is looking for any character zero or more times (.*
) up until the first space, and then capturing the one or more characters ((.+)
) after that first space. The ?
after .*
makes it "lazy" rather than "greedy" and is what makes it stop at the first space found. So, the .*?
matches everything before the first space, the space matches the first space found.
这篇关于使用gsub删除R中第一个空格之前的所有字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!