Jessie
Jessie

Reputation: 41

Make calculations using variables from 2 data frames

Data input:

df1:                            df2:
t1   Value1                     t2  Value2
2    10                         1   24
3    124                        2   32
4    88                         3   207
                                4   50
                                5   144

The formula should be used: Value3 = Value1*(t1-t2)/Value2 (condition: t1>=t2)

My approach:

#Create a function using the given formula
function1 = function(x,y){
  Value3 = x[,2] * (x[,1]-y[,1])/y[,2]
  return(Value3)
}

#
if (df1$t1 >= df2$t2) {
  lapply(list(df1, df2), FUN = function1)
}

#A new data frame df3 should be created including t1 & Value1 columns of df1 and new values calculated

My expected result: For example, for t1=2, we can make 2 calculations using t2=1, t2=2. e.g.(in my opinion),

t1  Value1   t2  Value 2   Value3
2   10       1   24        0.42
2   10       2   32        0

For t1=3: 3 calculations with t2 = 1,2,3 respectively and so on.

However, this code contains errors (probably because it's not applicable to use lapply to 2 different data frames in this case). How can I fix this issue? Thanks in advance.

Upvotes: 0

Views: 496

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 389095

You can try this approach :

do.call(rbind, Map(function(x, y) {
  val <- x >= df2$t2
  tibble::tibble(t1 = x, Value1 = y, t2 = df2$t2[val], 
                 Value2 = df2$Value2[val], Value3 = y * (x - t2)/Value2)
}, df1$t1, df1$Value1)) -> result

result

#     t1 Value1    t2 Value2 Value3
#  <int>  <int> <int>  <int>  <dbl>
#1     2     10     1     24  0.417
#2     2     10     2     32  0    
#3     3    124     1     24 10.3  
#4     3    124     2     32  3.88 
#5     3    124     3    207  0    
#6     4     88     1     24 11    
#7     4     88     2     32  5.5  
#8     4     88     3    207  0.425
#9     4     88     4     50  0    

Upvotes: 1

Peace Wang
Peace Wang

Reputation: 2419

Is this your expected result? I merge df1 and df2 as df in order to process easily later.

library(data.table)
df <- merge(df1,df2)
setDT(df)
df[,.SD[t1>=t2],by = t1][,.(Value3 = Value1*(t1-t2)/Value2)]

Result

       Value3
1:  0.4166667
2:  0.0000000
3: 10.3333333
4:  3.8750000
5:  0.0000000
6: 11.0000000
7:  5.5000000
8:  0.4251208
9:  0.0000000

or

df[t1>=t2,.(Value3 = Value1*(t1-t2)/Value2), by = t1]

#    t1     Value3
# 1:  2  0.4166667
# 2:  2  0.0000000
# 3:  3 10.3333333
# 4:  3  3.8750000
# 5:  3  0.0000000
# 6:  4 11.0000000
# 7:  4  5.5000000
# 8:  4  0.4251208
# 9:  4  0.0000000 

Data

df1 <- data.frame(
  t1 = c(2,3,4),
  Value1 = c(10,124,88)
)
df2 <- data.frame(
  t2 = 1:5,
  Value2 = c(24,32,207,50,144)
)

Upvotes: 3

Related Questions