1

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!

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

If I need to loop, there goes my efficiency!
@RicardoFernandesCampos no, it is not the case. Here, we are doing the loop by columns
I didn't know that. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.