0

Have:

> a <- 4
> a
[1] 4
> aDT <- data.table(a = c(1,2), b = c(NA,NA))
> aDT
   a  b
1: 1 NA
2: 2 NA

Need:

> aDT <- data.table(a = c(1,2), b = c(4,4))
> aDT
   a b
1: 1 4
2: 2 4

Tried:

> aDT[,b := rep(a, times = nrow(aDT))]

Warning messages: 1: In [.data.table(aDT, , :=(b, rep(a, times = nrow(aDT)))) : Supplied 4 items to be assigned to 2 items of column 'b' (2 unused) 2: In [.data.table(aDT, , :=(b, rep(a, times = nrow(aDT)))) : Coerced 'double' RHS to 'logical' to match the column's type; may have truncated precision. Either change the target column to 'double' first (by creating a new 'double' vector length 2 (nrows of entire table) and assign that; i.e. 'replace' column), or coerce RHS to 'logical' (e.g. 1L, NA_[real|integer]_, as.*, etc) to make your intent clear and for speed. Or, set the column type correctly up front when you create the table and stick to it, please.

As you can see, because the data table has a column whose name is the same as one of variables in the global environment. How to fix the code?

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
LeGeniusII
  • 900
  • 1
  • 10
  • 28

0 Answers0