Friday, September 22, 2017

tolower() toupper() {base}


tolower() and toupper() functions translate character vectors from upper to lower case, and from lower to upper case, respectively.

tolower(x) 
toupper(x)

The parameters are:
 - x: a character vector

tolower():
x = 'abcd, abcDEF, ABCDDEE, 1234'
x
## [1] "abcd, abcDEF, ABCDDEE, 1234"
tolower(x)
## [1] "abcd, abcdef, abcddee, 1234"
All the characters have been converted to lower case, and the numeric objects have been converted to characters.

toupper(x):
x
## [1] "abcd, abcDEF, ABCDDEE, 1234"
toupper(x)
## [1] "ABCD, ABCDEF, ABCDDEE, 1234"
All the characters have been converted to upper case, and the numeric objects have been converted to characters and have left unchanged.
head(airquality)
##   Ozone Solar.R Wind Temp Month Day
## 1    41     190  7.4   67     5   1
## 2    36     118  8.0   72     5   2
## 3    12     149 12.6   74     5   3
## 4    18     313 11.5   62     5   4
## 5    NA      NA 14.3   56     5   5
## 6    28      NA 14.9   66     5   6
par(mfrow= c(1,2))
boxplot(airquality[1:4], las = 2, col = c('aquamarine', 'aquamarine2', 'aquamarine3', 'aquamarine4'))
boxplot(airquality[1:4], names = c(toupper(colnames(airquality[1:4]))), las = 2, col = c('violet', 'violetred1', 'violetred3', 'violetred4'))

Function to capitalized just the first letter:
#Example capitalizing first letter of word 'hello':
paste(toupper(substring('hello', 1, 1)), substring('hello', 2),
          sep = "", collapse = " ")
## [1] "Hello"
#Function:
simpleCap =function(x) {
    s =strsplit(x, " ")[[1]]
    paste(toupper(substring(s, 1, 1)), substring(s, 2),
          sep = "", collapse = " ")}

y = 'hi, how are you?'
z = c('abcd', 'bbddee', 1234)
simpleCap(y) 
## [1] "Hi, How Are You?"
simpleCap(z) #the function just capitalized the first element in a list, and z is a vector of elements. Just the first element will be used.
## [1] "Abcd"
par(mfrow = c(1,3), oma=c(0,0,2,0))
boxplot(weight ~ feed, data = chickwts,ylab = "Weight at six weeks (gm)", las =2, col = topo.colors(6, 0.5))
boxplot(weight ~ feed, data = chickwts, names = toupper(levels(chickwts$feed)), ylab = "Weight at six weeks (gm)", las = 2, col = cm.colors(6))
boxplot(weight ~ feed, data = chickwts, names = sapply(levels(chickwts$feed), simpleCap),ylab = "Weight at six weeks (gm)", las = 2, col=colors(6))
title(main = 'Diferences in the labels using `chickwt` dataset', outer = TRUE)

No comments:

Post a Comment

duplicated() {base}

duplicated()  function determines which elements are duplicated and returns a logical vector. The parameters of the function are:   ...