You can use regular expressions like
sub(" .*", "", x)
See a demo of regular expressions .
Here, sub will only perform one search and replace operation, a pattern .* Find the first space (since the regex engine looks for strings from left to right), a .* Matches any zero or more characters (in the TRE regex variant, even including line break characters, be careful when using perl=TRUE , then this is not) as much as possible, up to the end of the line.
Some options:
sub("[[:space:]].*", "", x) # \s or [[:space:]] will match more whitespace chars sub("(*UCP)(?s)\\s.*", "", x, perl=TRUE) # PCRE Unicode-aware regex stringr::str_replace(x, "(?s) .*", "") # (?s) will force . to match any chars
Watch online R demo .
source share