Data function runs in RStudio but not in TERR?!

Hi..

I'm using this R script to manipulate a data set and add extra columns. My problem is that when I run this in RStudio, it works perfectly fine for all columns. When I run this as a data function in Spotfire on the same dataset, I get an error on column L3. Is anybody able to advise?

dataset:

ID,L1,L2,L3
1,BBCBCACCBCB,CBCBBBB,BEBBBAAB
2,BBCBCCCCBCB,CBCCCBC,BBAACCCB
3,BBCBCACCBCB,CBCBBBB,BEBBBAAB
4,BBCBCACCBCB,CBCBBBB,BEBBBAAB
5,BBCBACBCCCB,BBCCCBC,BBCBAAAAB
6,BBCBBCCBBCB,BBCBCEB,BBBBCAACB
7,BBCBBCCBBCB,BBCBCEB,BBBBCAACB
8,,,
9,BBCBCACCBCB,CBCBBBB,BEBBBAAB
10,BBCBBCCBBCB,BBCBCEB,BBBBCAACB
11,BBCBBCCBBCB,BBCBCEB,BBBBCAACB

data function:

foo = function(data, column){
    temp_L1 = lapply(as.character(data[[column]]), function(x) sapply(3:nchar(x), function(i) substr(x, i-2, i)))
    temp_L1_length = max(lengths(temp_L1))
    temp_L1 = lapply(temp_L1, function(x)
        sapply(x, function(y){
            num_a = unlist(gregexpr(pattern = "a", text = y, ignore.case = TRUE))
            num_a = sum(num_a > 0)  #length of positive match
            num_b = unlist(gregexpr(pattern = "b", text = y, ignore.case = TRUE))
            num_b = sum(num_b > 0)
            num_c = unlist(gregexpr(pattern = "c", text = y, ignore.case = TRUE))
            num_c = sum(num_c > 0)
            num_a * 1 + num_b * 3 + num_c * 7
        })
    )
    temp_L1 = setNames(data.frame(do.call(rbind, lapply(temp_L1, function(a)
        a[1:temp_L1_length]))), nm = paste0(column,"_",1:temp_L1_length))
    return(temp_L1)
}

finaldata <- cbind(df, do.call(cbind, lapply(colnames(df)[-1], function(x) foo(data = df, column = "L3"))))

Login