I am trying to write a function for calculating surprisal for each new value in a list. Here is a dummy example:
x <- c('A','A','C','D','A','A','D','A','B','A','A')
surprise <- function(x){
sur <-c()
for (i in x){
num <- sum(x[1:i] == x[i])
denom <- length(x[1:i])
sur[i] <- -log2((num)/(denom-1+4))
}}
My for loop yields this error, even though if I manually insert values for i, everything seems to work:
Error in 1:i : NA/NaN argument In addition: Warning message: In 1:i : NAs introduced by coercion
I also know there is probably a way to write this without for loops - any suggestions welcome!