mql4beginner mql4beginner - 1 year ago 71
R Question

How to add calculation results to another dataset based on a filter

I have two datasets and I need to add a value that is based on specific levels of the two variables' values.I need to add to

dat dataset
the value that is calculated on the
dat1 dataset
so the output should be like in
dat2
.Any idea how to this ( the values in dat1 are text)?

dat3 <- read.table(text = " lamps vases
7 9
1 6
3 5
7 8
5 4
1 3
0 7
6 6
8 9 ", header = TRUE)

dat2 <- read.table(text = " lamps vases est
3,5 4,5 0.6
8 9 0.4
", header = TRUE)
dat2 <- read.table(text = " lamps vases est
7 9 0
1 6 0
3 5 0.6
7 8 0
5 4 0.6
1 3 0
0 7 0
6 6 0
8 9 0.4", header = TRUE)

Answer Source

We can try with tidyverse. Convert the second dataset 'dat2' (with 2 rows in the OP's post) into 'long' format by splitting the 'lamps', 'vases' column (separate_rows), left_join with the first dataset ('df1' - labelled as 'df3' in OP's post), and with replace_na change the NA in 'est' to 0

library(tidyverse)
separate_rows(dat2, lamps, convert = TRUE) %>% 
    separate_rows(vases, convert = TRUE) %>% 
    left_join(dat1, ., by = c("lamps", "vases")) %>%
    replace_na(list(est = 0))
#   lamps vases est
#1     7     9 0.0
#2     1     6 0.0
#3     3     5 0.6
#4     7     8 0.0
#5     5     4 0.6
#6     1     3 0.0
#7     0     7 0.0
#8     6     6 0.0
#9     8     9 0.4
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download