3

Let's assume I have the following code:

x = data.table(rowid=1:10, N1=2:11, N2=3:12, N3=4:13)
x[, sum(c(N1, N2, N3)),by=rowid]

Now assume I don't know the column names N1, N2, N3 in advance and they are saved in the vector colnames=c("N1", "N2", "N3"). If I know the number of variables to pass to sum(), I can plug in colnames as follows:

x[, sum(c(get(colnames[1]),get(colnames[2]),get(colnames[3]))),by=rowid]

Now assume I don't know the length of colnames. Is there any way I can rewrite the above so it works? Something like x[, sum(c(sapply(colnames, as.name))),by=rowid] (note this exact expression doesn't work).

1 Answer 1

5

This sums all columns except rowid :

x[, sum(.SD), by = rowid]

This sums only those columns named in character vector colnames :

x[, sum(.SD), by = rowid, .SDcols = colnames]

In both cases the sums are by rowid .

Sign up to request clarification or add additional context in comments.

Comments

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.