apply chartr lapply nchar paste readLines substr trimws
m <- matrix(c(1:10, 11:20, 10:1), nrow = 5, ncol = 3)
m
# Output:
[,1] [,2] [,3]
[1,] 1 6 11
[2,] 2 7 12
[3,] 3 8 13
[4,] 4 9 14
[5,] 5 10 15
# Find medians of rows
apply(m, 1, median)
# Output:
[1] 6 7 8 9 10
# Find means of columns
apply(m, 2, mean)
# Output:
[1] 3 8 13
chartr("acg", "hdb", "class assignment")
# Output:
[1] "dlhss hssibnemnt"
v <- c("class", "assignment")
chartr("acg", "hdb", v)
# Output:
[1] "dlhss" "hssibnemnt"lst <- list(a=c(1, 2), b=c(3, 4, 5)) lapply(lst, sum) # Output: $a [1] 3 $b [1] 12
v <- c("one", "two", "three", "four")
nchar(v)
# Output:
[1] 3 3 5 4
a <- c(1,2,3)
b <- c("a","b","c")
paste(a, b, sep=";")
# Output:
[1] "1 a" "2 b" "3 c"
paste(a, b, sep=";")
# Output:
[1] "1;a" "2;b" "3;c"
paste(a, b, sep="")
# Output:
[1] "1a" "2b" "3c"
# Input file
This
is
a
test.
# Read to end of file
con <- file("input.txt")
lines <- readLines(con)
close(con)
print(lines)
# Output:
[1] "This" "is" "a" "test."
# Read first 2 lines of file.
con <- file("input.txt")
lines <- readLines(con, n=2)
close(con)
print(lines)
# Output:
[1] "This" "is"
lines <- readLines("input.txt", n=2)
print(lines)
If the filename is used in the readLines function, reading
always starts at the beginning of the file, whereas with
a connection object, reading resumes with the next line after the last line that was read
on the previous call to readLines. Close each connection
object after you are finished reading from it.
v <- c("apple,elephant,student")
strsplit(v, ",")
# Output:
[[1]]
[1] "apple" "elephant" "student"
w <- c("apple,elephant,student", "abc;xyx")
strsplit(v, c(",", ";"))
# Output:
[[1]]
[1] "apple" "elephant" "student"
[[2]]
[1] "abc" "xyx"
substr("abcdefg", 3, 5)
# Output:
[1] "cde"
v <- c("abcdefg", "mnopqrst", "wxyz")
substr(v, 3, 5)
# Output:
[1] "cde" "opq" "yz"
substr(v, 1:3, 2:4)
# Output:
[1] "ab" "no" "yz"
v <- c(" abc ", " cde ", " xyz ")
trimws(v, which="both")
# Output:
[1] "abc" "cde" "xyz"
trimws(str, which="left")
# Output:
[1] "abc " "cde " "xyz "
trimws(str, which="right")
# Output:
[1] " abc" " cde" " xyz"