Reputation: 65
Say we have some data
w <- 1:3
x <- 5:7
y <- c(3, 2, 3)
z <- c(3, 2, 5)
df <- data.frame(w,x,y,z)
Then I wish to create a new vector which runs the following
apply(df, 1, function(data) sum(2^(seq_along(data)) * data))
How can I run this apply
function in Tidyverse?
I'm finding issues relating to that the data is the input rather than a specific column.
Upvotes: 1
Views: 79
Reputation: 99331
You could ditch the loop and the packages, and simply do
rowSums(2^col(df) * df)
# [1] 94 76 138
col(df)
gives you a matrix where the column values are the column numbers. So you can use that for your exponent, multiply by the original data, take the row sums, and avoid any loops or packages all together.
Upvotes: 3