Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从R中的字符串中提取前2个单词?_R_String - Fatal编程技术网

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

如何从R中的字符串中提取前2个单词?,r,string,R,String,我需要从字符串中提取前两个单词。如果字符串包含2个以上的单词,则应返回前2个单词;如果字符串包含的单词少于2个,则应按原样返回字符串 我曾尝试使用stringr包中的“word”函数,但对于len(string)

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

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

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

输入字符串:其他 输出:其他类似的东西

a <- "this is a character string"

unlist(strsplit(a, " "))[1:2]

[1] "this" "is" 

a如果要使用
stringr::word()
,可以执行以下操作:

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

[1] "Auto Loan" "Others" 
样本数据:

x <- c("Auto Loan (Personal)", "Others")

x您可以使用
sub

sub("(\\w+\\s+\\w+).*", "\\1", "Auto Loan (Personal)")
#[1] "Auto Loan"
如果文本中只有一个单词,这也会起作用

sub("(\\w+\\s+\\w+).*", "\\1", "Auto")
#[1] "Auto"
说明:

在这里,我们提取圆括号内显示的模式,它是
(\\w+\\s+\\w+
,意思是:


\\w+
一个单词后接
\\s+
空格后接
\\w+
另一个单词,因此我们总共提取了两个单词。提取是使用
sub

中的backreference
\\1
完成的。您能详细解释一下这个部分吗?\\w+\\s+\\w+.*”,“\\1”?
sub("(\\w+\\s+\\w+).*", "\\1", "Auto Loan (Personal)")
#[1] "Auto Loan"
sub("(\\w+\\s+\\w+).*", "\\1", "Auto")
#[1] "Auto"