gpt4 book ai didi

r - 获取第一个空格之前的字符

转载 作者:行者123 更新时间:2023-12-02 03:50:44 24 4
gpt4 key购买 nike

我正在寻找一种 gr​​ep 方法来获取字符串中第一个空格之前的字符。

我已经破解了以下函数,因为我无法弄清楚如何使用R中的grep类型命令来实现它。

有人可以帮助解决 grep 解决方案吗 - 如果有的话......

beforeSpace <- function(inWords) {
vapply(inWords, function(L) strsplit(L, "[[:space:]]")[[1]][1], FUN.VALUE = 'character')
}
words <- c("the quick", "brown dogs were", "lazier than quick foxes")
beforeSpace(words)

R> the quick brown dogs were lazier than quick foxes
"the" "brown" "lazier"

并且请告诉我是否有比 grep (或我的函数 beforeSpace)更好的方法来执行此操作。

最佳答案

或者只是sub,归功于@flodel:

sub(" .*", "", words)
# and if the 'space' can also be a tab or other white-space:
sub("\\s.*","",words)
#[1] "the" "brown" "lazier"

关于r - 获取第一个空格之前的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25477920/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com