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

R toupper() and tolower() Functions - Case Conversion

R toupper() and tolower() Functions - Case Conversion

R Language Examples R Language Examples

The R toupper() function converts strings to uppercase, and tolower() converts them to lowercase.

During data cleaning and text preprocessing, unifying case is a common operation.

The syntax of these two functions is as follows:

toupper(x)

tolower(x)

Parameter Description:

Example

text

<-

"Hello RUNOOB World"

Convert to uppercase

print

(

toupper

(

text

)

)

Convert to lowercase

print

(

tolower

(

text

)

)

Case conversion in a vector

words

<-

c

(

"Apple"

,

"Banana"

,

"Cherry"

)

print

(

"All uppercase:"

)

print

(

toupper

(

words

)

)

print

(

"All lowercase:"

)

print

(

tolower

(

words

)

)

The output of the code above is:

[1] "HELLO RUNOOB WORLD"

[1] "hello runoob world"

[1] "全部大写:"

[1] "APPLE"  "BANANA" "CHERRY"

[1] "全部小写:"

[1] "apple"  "banana" "cherry"

Case conversion is often used for standardization before data matching:

Example

Compare after unifying to lowercase

user_input

<-

"RunOOb"

standard

<-

tolower

(

user_input

)

if

(

standard

==

"runoob"

)

{

 

print

(

"Match successful!"

)

}

Capitalize the first letter (custom function)

capitalize

<-

function

(

x

)

{

  paste0

(

toupper

(

substr

(

x,

1

,

1

)

)

,

         

tolower

(

substr

(

x,

2

,

nchar

(

x

)

)

)

)

}

print

(

capitalize

(

c

(

"hello"

,

"WORLD"

,

"rUnoob"

)

)

)

The output of the code above is:

[1] "匹配成功!"

[1] "Hello"  "World"  "Runoob"

R Language Examples R Language Examples