David Moore
David Moore

Reputation: 1010

Defining a function that includes for loops

I have 2 data frames.

One (df1) has columns for slopes and intercepts, and the other (df2) has an index column (i.e., row numbers).

I wish to apply a function based on parameters from df1 to the entire index column in df2. I don't want the function to mix and match slopes and intercepts (i.e., I want to make sure that the function always uses slopes and intercepts from the same columns in df1).

I tried to do this

my_function <- function(x) {for (i in df1$slope) for (j in df1$intercept) {((i*x)+j)}}

df3 <- for (k in df2$Index) {my_function(k)}

df3

but it didn't work.

Here are sample data:

> df1
  thermocouple slope intercept
1            1  0.01       0.5
2            2 -0.01       0.4
3            3  0.03       0.2
> df2
  index    t_1    t_2    t_3
1     1    0.3    0.2    0.2
2     2    0.5    0.2    0.3
3     3    0.3    0.9    0.1
4     4    1.2    1.8    0.4
5     5    2.3    3.1    1.2

Here would be the output I need:

index    baseline_t_1    baseline_t_2    baseline_t_3
1        0.51            0.39            0.23
2        0.52            0.38            0.26
3        0.53            0.37            0.29
4        0.54            0.36            0.32
5        0.55            0.35            0.35

What am I doing wrong?

Thanks!

Upvotes: 0

Views: 43

Answers (1)

Sathish
Sathish

Reputation: 12723

Try this:

By passing three arguments with values at the same time to a anonymous function defined in Map.

Map( function(index, slope, intercept) (index * slope ) + intercept,
     index = df2$Index, slope = df1$slope, intercept = df1$intercept)

May be this: I am not sure which one you prefer given there is no data and expected output in the question.

lapply( df2$index, function(index){
  unlist( Map( function(slope, intercept) (index * slope ) + intercept,
               slope = df1$slope, intercept = df1$intercept) )
})

Upvotes: 1

Related Questions