I have a list of vectors stored
library(seqinr) mydata <- read.fasta(file="mydata.fasta")
mydatavec <- mydata[[1]]
lst <- split(mydatavec, as.integer(gl(length(mydatavec), 100,length(mydatavec))))
df <- data.frame(matrix(unlist(lst), nrow=2057, byrow=T), stringsAsFactors=FALSE)
Now, each vector in df is 100 long and made up of letters "a", "c", "g", "t". I would like to calculate Shannon entropy of each of these vector, I will give example of what I mean:
v1 <- count(df[1,], 1)
a c g t
27 26 24 23
v2 <- v1/sum(v1)
a c g t
0.27 0.26 0.24 0.23
v3 <- -sum(log(v2)*v2) ; print(v3)
[1]1.384293
In total I need 2057 printed values because that is how many vectors I have. My question here, is it possible to create a for loop or repeat loop that would do this operation for me? I tried myself but I didn't get nowhere with this.
dput(head(sequence))
structure(c("function (nvec) ", "unlist(lapply(nvec, seq_len))"
), .Dim = c(2L, 1L), .Dimnames = list(c("1", "2"), ""), class = "noquote")
My attempt: I wanted to focus on the count function only and created this
A <- matrix(0, 2, 4)
for (i in 1:2) {
A[i] <- count(df[i,], 1)
}
What the function does is it correctly calculates number of "a" in the first vector and then follows to the second one. It completely ignores the rest of the letters
A
[,1] [,2] [,3] [,4]
[1,] 27 0 0 0
[2,] 28 0 0 0
Additionally I naively thought that adding bunch of "i" everywhere will make it work
s <- matrix(0, 1, 4)
s1 <- matrix(0, 1, 4)
s2 <- numeric(4)
for (i in 1:2) {
s[i] <- count(df[i,],1)
s1[i] <- s[i]/sum(s[i])
s2[i] <- -sum(log(s1[i])*s1[i])
}
But that didn't get me anywhere either.
dput(head(mydata))?dput(head(mydata))?