Reputation: 911
I'm trying to change lines and columns in data.table using set
for efficiency.
The documentation on set
states that the argument j is:
"Column name(s) (character) or number(s) (integer) to be assigned value when column(s) already exist, and only column name(s) if they are to be created."
and value argument is: "A list of replacement values to assign by reference to x[i, j]."
However, I'm getting an error. This is an example code:
iris = as.data.table(iris)
set(iris,i=1L,j=as.integer(1:3),value=list(1:3))
this is the error I'm getting:
Error in set(iris, i = 1L, j = as.integer(1:3), value = list(1:3)) : Supplied 3 items to be assigned to 1 items of column 'Sepal.Length'. If you wish to 'recycle' the RHS please use rep() to make this intent clear to readers of your code.
I know I can use the other alternatives to assign it, but set
is MUCH more efficient. I'd like to know if this is possible.
Thanks!
Upvotes: 1
Views: 85
Reputation: 886938
If we are using set
for multiple columns, then loop it
library(data.table)
for(j in 1:3) set(iris, i = 1L, j = j, value = j)
head(iris, 2)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1: 1.0 2.0 3.0 0.2 setosa
#2: 4.9 3.0 1.4 0.2 setosa
In base R
, this can be done more easily
data(iris)
iris[1, 1:3] <- as.list(1:3)
head(iris, 2)
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#1 1.0 2 3.0 0.2 setosa
#2 4.9 3 1.4 0.2 setosa
Upvotes: 1