Raquel Feltrin
Raquel Feltrin

Reputation: 147

create a new list from 2 other list with conditions

I have two large list (more than 10 elements) and I want to apply a function in one of the the list based on the other one. So one of my list has elements with temperature (list1) and the other has elements with heat transfer coefficient (list2). I want to apply the function (x*0.6/k) where x is the values in list2 and k will vary according to list1. For example if temperature is equal 20C, k is 0.02514.

I am going to use one element of each list as a data frame here to better illustrate what I am trying to do.

list1_element1 <- data.frame("0" = c(20, 150, 120),
                             "10" = c(20, 800, 120)) 

list2_element2 <- data.frame("0" = c(8, 10, 6),
                             "10" = c(10, 9, 8)) 

            

here is the conditions for k

if 0 < X <= 20 in list 1, k=0.02514
if 100 < X <= 200 in list 1 = 100, k=0.03095
if 700 < X <= 800 in list 1 = 800, k=0.07037

Applying the function x*0.6/k in list 2, this is the result I am looking for

list3_element1<- data.frame("0" = c(190.93, 193.86, 116.31 ),
                     "10" = c(238.66, 76.73, 155.08))

To clarify, I want to apply the function in list2_element2 using the conditions of k based on list1_element1. The same I want to do for element2 (apply the function in list2_element2 with k based on list1_element1) and so on.

I hope I was clear about what I am trying to do. So any help is very much appreciated because I am not sure from where to start. Thank you.

Upvotes: 0

Views: 48

Answers (1)

Sotos
Sotos

Reputation: 51582

You can create a data frame with the mapped coefficients. I used a nested ifelse statement since you only have 3 conditions. cut() can be used for efficiency and multiple conditions.

d1 <- data.frame(ifelse(list1_element1 <= 20, 0.02514, 
                        ifelse(list1_element1 > 100 & list1_element1 <= 200, 0.03095, 
                               ifelse(list1_element1 > 700 & list1_element1 <= 800, 0.07037, NA))))

mapply(function(x, y)x * 0.6 / y, list2_element2, d1)

           X0       X10
[1,] 190.9308 238.66348
[2,] 193.8611  76.73725
[3,] 116.3166 155.08885

Upvotes: 1

Related Questions