Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R trimws() Function - Removing Whitespace

R trimws() Function - Removing Whitespace

R Language Examples R Language Examples

The R trimws() function is used to remove leading and trailing whitespace (spaces, tabs, newlines, etc.).

In data cleaning, trimws() can remove extra spaces accidentally included in user input.

The syntax of the trimws() function is as follows:

trimws(x, which = c("both", "left", "right"))

Parameter Description:

Example

text

<-

"  Hello RUNOOB  "

Remove whitespace from both sides

result1

<-

trimws

(

text

)

print

(

result1

)

Remove only leading whitespace

result2

<-

trimws

(

text

,

which

=

"left"

)

print

(

"Left only:"

)

print

(

result2

)

Remove only trailing whitespace

result3

<-

trimws

(

text

,

which

=

"right"

)

print

(

"Right only:"

)

print

(

result3

)

Process a vector

names_with_spaces

<-

c

(

" Zhang San "

,

" Li Si"

,

"Wang Wu "

)

cleaned_names

<-

trimws

(

names_with_spaces

)

print

(

"Cleaned names:"

)

print

(

cleaned_names

)

The output of the code above is:

[1] "Hello RUNOOB"

[1] "只去左侧:"

[1] "Hello RUNOOB  "

[1] "只去右侧:"

[1] "  Hello RUNOOB"

[1] "清理后的名字:"

[1] "张三" "李四" "王五"

R Language Examples R Language Examples