String in R

Category:R

split

split a string into a vector:

x = "string_x"
strsplit(x, split="")
[[1]]
[1] "s" "t" "r" "i" "n" "g" "_" "x"

paste

x = paste("Hello", "World", sep=", ")
print(x)
[1] "Hello, World"
chars = c("m", "e", "r", "g", "e", "d")
paste(chars, collapse = "")
[1] "merged"

toString

x = c("Hello", "World")
y = toString(x)
print(y)
[1] "Hello, World"

ps: it seems "format" is also an useful function.

chartr

x = "ACGTGTGACGT"
y = chartr("acgtACGT","tgcaTGCA",x)
print(x);print(y)
[1] "ACGTGTGACGT"
[1] "TGCACACTGCA"

DNA Reverse Complementary

DNA.Rev.Comp <- function(x) {
	if (is.character(x) && length(x) == 1) {
		x = chartr("acgtACGT","tgcaTGCA",x)
		x = unlist(strsplit(x,split=""))
		x = rev(x)
		x = paste(x,collapse="")
		return(x)
	}
	else {
		warning("Wrong argument type in DNA.Rev.Comp, NA returned")
		return(NA)
	}
}

DNA.Rev.Comp("ACTGTGACCACGTCGTA")
[1] "TACGACGTGGTCACAGT"
Homepage
Comments

Hide Comments