Dekike
Dekike

Reputation: 1284

How to create a new column in a data frame depending on multiple criteria from multiple columns from the same data frame

I have a data frame df1 with four variables. One refers to sunlight, the second one refers to the moon-phase light (light due to the moon's phase), the third one to the moon-position light (light from the moon depending on if it is in the sky or not) and the fourth refers to the clarity of the sky (opposite to cloudiness).

I call them SL, MPhL, MPL and SC respectively. I want to create a new column referred to "global light" that during the day depends only on SL and during the night depends on the other three columns ("MPhL", "MPL" and "SC"). What I want is that at night (when SL == 0), the light in a specific area is equal to the product of the columns "MPhL", "MPL" and "SC". If any of them is 0, then, the light at night would be 0 also.

Since I work with a matrix of hundreds of thousands of rows, what would be the best way to do it? As an example of what I have:

SL<- c(0.82,0.00,0.24,0.00,0.98,0.24,0.00,0.00)
MPhL<- c(0.95,0.85,0.65,0.35,0.15,0.00,0.87,0.74)
MPL<- c(0.00,0.50,0.10,0.89,0.33,0.58,0.00,0.46)
SC<- c(0.00,0.50,0.10,0.89,0.33,0.58,0.00,0.46)
df<-data.frame(SL,MPhL,MPL,SC)
df
    SL MPhL  MPL   SC
1 0.82 0.95 0.00 0.00
2 0.00 0.85 0.50 0.50
3 0.24 0.65 0.10 0.10
4 0.00 0.35 0.89 0.89
5 0.98 0.15 0.33 0.33
6 0.24 0.00 0.58 0.58
7 0.00 0.87 0.00 0.00
8 0.00 0.74 0.46 0.46

What I would like to get is this:

df
    SL MPhL  MPL   SC   GL
1 0.82 0.95 0.00 0.00 0.82 # When "SL">0, GL= SL
2 0.00 0.85 0.50 0.50 0.21 # When "SL" is 0, GL = MPhL*MPL*SC
3 0.24 0.65 0.10 0.10 0.24
4 0.00 0.35 0.89 0.89 0.28
5 0.98 0.15 0.33 0.33 0.98
6 0.24 0.00 0.58 0.58 0.24
7 0.00 0.87 0.00 0.00 0.00
8 0.00 0.74 0.46 0.46 0.16

Upvotes: 1

Views: 41

Answers (1)

Cettt
Cettt

Reputation: 11981

the most simple way would be to use the ifelse function:

GL <- ifelse(SL == 0, MPhL * MPL * SC, SL)

If you want to work in a more structured environment, I can recommend the dplyr package:

library(dplyr)
tibble(SL = SL, MPhL = MPhL, MPL = MPL, SC = SC) %>% 
  mutate(GL = if_else(SL == 0, MPhL * MPL * SC, SL))
    # A tibble: 8 x 5
     SL  MPhL   MPL    SC       GL
  <dbl> <dbl> <dbl> <dbl>    <dbl>
1  0.82  0.95  0.00  0.00 0.820000
2  0.00  0.85  0.50  0.50 0.212500
3  0.24  0.65  0.10  0.10 0.240000
4  0.00  0.35  0.89  0.89 0.277235
5  0.98  0.15  0.33  0.33 0.980000
6  0.24  0.00  0.58  0.58 0.240000
7  0.00  0.87  0.00  0.00 0.000000
8  0.00  0.74  0.46  0.46 0.156584

Upvotes: 1

Related Questions