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.

Here's one way to do it.

library(tidyverse)

df1 <- tribble(
    ~a, ~x, ~y, ~z,
    1,  2,  3,  4,
    5,  6,  7,  8
)

# exponents
# more convenient if a is in here as well.  a number raised to power 0 is unchanged.
df2 <- tribble(
    ~a, ~x, ~y, ~z,
    0,  2,  4,  6
)

df1$result <- (df1 ^ df2[rep(1, nrow(df1)), ]) %>% apply(1, prod)
df1
#> # A tibble: 2 x 5
#>       a     x     y     z      result
#>   <dbl> <dbl> <dbl> <dbl>       <dbl>
#> 1     1     2     3     4     1327104
#> 2     5     6     7     8 22658678784

Created on 2021-06-08 by the reprex package (v1.0.0)

1 Like

Works a charm. Thank you very much :+1:

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.