0

Given a data table with 3 columns (the first two form the key), I'm trying to add a bunch of columns x_k with k running from 1 to N

df
>    a    b    c 
1:   1    1    1
2:   1    2    1
3:   1    3    2

For each new column x_k, its value is calculated by the equation cos(2 * pi * c / k) grouped by a and b.

My approach doesn't seem to work: generating a list of column names then parsing it

df[, eval(parse(text = paste0(paste0("x_", 1:N), " := cos(2 * pi * c / ", 1:N, ")"))), by = .(a,b)]

R said c not found. How should i correct my approach other than looping through list of column names ?

1 Answer 1

4

Maybe try something like:

df[, paste0("x_", 1L:N) := lapply(1L:N, function(k) cos(2 * pi * c / k)), .(a, b)]
Sign up to request clarification or add additional context in comments.

4 Comments

That's exactly what i came to after posting the question :D
Pls feel free to answer your own question or delete.
I think i'll leave it here for later reference.
I would use seq_len(N)

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.