gpt4 book ai didi

r - 如何从R中的字符串中提取前2个单词?

转载 作者:行者123 更新时间:2023-12-04 10:15:50 26 4
gpt4 key购买 nike

我需要从字符串中提取前 2 个单词。如果字符串包含 2 个以上的单词,则应返回前 2 个单词,否则,如果字符串包含的单词少于 2 个,则应按原样返回字符串。

我已经尝试使用 stringr 包中的“word”函数,但对于 len(string) < 2 的情况,它没有提供所需的输出。

word(dt$var_containing_strings, 1,2, sep=" ")

例子:
输入字符串:汽车贷款(个人)
输出:汽车贷款

输入字符串:其他
输出:其他

最佳答案

如果你想使用 stringr::word() ,你可以这样做:

ifelse(is.na(word(x, 1, 2)), x, word(x, 1, 2))

[1] "Auto Loan" "Others"

样本数据:
x <- c("Auto Loan (Personal)", "Others")

关于r - 如何从R中的字符串中提取前2个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57091214/

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