Nneka
Nneka

Reputation: 1860

$ operator is invalid for atomic vectors in data.table inside a function in R

I am using an function:

if(nrow(product$productCC) > 0){

product$productCC$type

claimsInvoice[, CCtype := product$productCC$type]  
claimsInvoice[,  ':=' (CCtype = product$productCC$type)]   

}

but i both cases I get an error. I though by using ':=' was a functional form?

> product$productCC$type
[1] "GENERAL_CAP_PER_YEAR"
> claimsInvoice[, CCtype := product$productCC$type] 
Error in product$productCC : $ operator is invalid for atomic vectors

How can this be fixed?

EDIT:

i tried using

type <- product$productCC$type
claimsInvoice[,  ':=' (CCtype = type)] 

instead of

claimsInvoice[, CCtype := product$productCC$type] 

to avoid the scoping issues as mentioned by @chinsoon12, but that results in another error :

Warning message:
In `[.data.table`(claimsInvoice, , `:=`(CCtype = type)) :
  Coercing 'character' RHS to 'logical' to match the type of the target column (column 13 named 'CCtype').

Upvotes: 1

Views: 374

Answers (1)

r2evans
r2evans

Reputation: 160447

The issue (I think) is the NSE evaluation of values, compounded by the convenience that data.table::[ operations tend to give the user. One way to step around it is to the set, which is both simpler (no NSE) and at times faster than data.table::[ and its := assignment.

claimsInvoice <- data.table(x = 1, product = 2)
product <- list(productCC = list(type = "GENERAL_CAP_PER_YEAR"))

### no surprise
claimsInvoice[, CCtype := product$productCC$type ]
# Error in product$productCC : $ operator is invalid for atomic vectors
### works
set(claimsInvoice, j = "CCtype", value = product$productCC$type)

claimsInvoice
#    x product               CCtype
# 1: 1       2 GENERAL_CAP_PER_YEAR
str(claimsInvoice)
# Classes 'data.table' and 'data.frame':    1 obs. of  3 variables:
#  $ x      : num 1
#  $ product: num 2
#  $ CCtype : chr "GENERAL_CAP_PER_YEAR"
#  - attr(*, ".internal.selfref")=<externalptr> 

Upvotes: 2

Related Questions