Monday, August 20, 2018

Strange tibble behavior?

This seems like strange tibble behavior to me. I want to output the sum of a subset of every row in a tibble.

I can't figure out why this works...

tbl <- tibble(x=c(1,2,3),y=c(9,10,11))  

for (i in 1:nrow(tbl)){
   print(sum(tbl[i, c('x','y')]))
}

[1] 10
[1] 12
[1] 14

But this doesn't work.

fun <- function(row){
    return (sum(row[c('x','y')]))
}
apply(tbl, 1, fun)


Error in sum(record[c("x", "y")]) : 
   invalid 'type' (character) of argument

As it turns out my numbers in tbl are being converted into chars.

fun2 <- function(row){
    print (row[c('x','y')])
}
apply(tbl,1,fun2)

   x    y 
 "1" " 9" 
   x    y 
 "2" "10" 
   x    y 
 "3" "11" 
  [,1] [,2] [,3]
x "1"  "2"  "3" 
y " 9" "10" "11"

Why does are these values being converted into strings?

No comments:

Post a Comment