Very new to R, trying to use it like Excel and coming unstuck pretty fast.
Code below is likely more helpful than my description.
I'd like to do a fairly simple calculation to each value of "a" in a tibble, based on the values of the other columns in that tibble and an index which comes from a separate tibble.
Doing this long-hand works just fine, unless I was to have many more columns. I can't figure out a better way to do it. Had a go with a for loop, but I don't think I was referencing the values properly.
Is there perhaps a better way to format my tables to make it work better for R, maybe use only 1 table for everything, or perhaps have "a" as a separate 1 column table?
Thanks
library(tidyverse)
df1 <- tribble(
~a, ~x, ~y, ~z,
1, 2, 3, 4,
5, 6, 7, 8
)
df2 <- tribble(
~x, ~y, ~z,
2, 4, 6
)
# Long hand - works but impractical to scale up
df1 %>%
mutate(a = a *
x ^ df2$x *
y ^ df2$y *
z ^ df2$z)
# Short hand attempt
names <- colnames(df1)
for (i in seq_along(names)) {
df1$a <- df1$a * df1[[names[i]]] ^ df2[[names[i]]]
}
The second attempt give the following error:
Error: Assigned data df1$a * df1[[names[i]]]^df2[[names[i]]]
must be compatible with existing data.
x Existing data has 2 rows.
x Assigned data has 0 rows.
i Only vectors of size 1 are recycled.
Run rlang::last_error()
to see where the error occurred.