0

I have "reference data" that contain depth values and corresponding levels up to n number levels as follows;

depth   levels
0.06    1
0.19    2
0.33    3
0.48    4
0.63    5
0.8     6

I have another "data file" in csv as follows.

Date    Levels  variable
3-Jan   1       15.25
3-Feb   5       13.09
3-Mar   25      14.21
3-Apr   26      13.65
3-May   27      12.79
3-Jun   27      15.65

In this "data file" I have levels in 3rd column which is needed to change as per the "reference data". That means if level is 1 in the "data file" I need to replace that value '1' with its corresponding depth values from "reference data", i.e., 0.06. Like that, I want to change the whole values in the second column of my "data file".

So far I have tried mapvalues and match. But no luck.

user438383
  • 5,716
  • 8
  • 28
  • 43

1 Answers1

1

I think you want to merge the two datasets using the level. Then for each date you would have variable and depth, and you can do what you want with that (including overwriting the level with the depth, as you suggest).

library(tidyverse)
reference_data <- read_table("depth   levels
0.06    1
0.19    2
0.33    3
0.48    4
0.63    5
0.8     6")

data_file <- read_table("Date    Levels  variable
3-Jan   1       15.25
3-Feb   5       13.09
3-Mar   25      14.21
3-Apr   26      13.65
3-May   27      12.79
3-Jun   27      15.65")

data_file %>% 
  left_join(reference_data, by = c("Levels" = "levels"))
#> # A tibble: 6 x 4
#>   Date  Levels variable depth
#>   <chr>  <dbl>    <dbl> <dbl>
#> 1 3-Jan      1     15.2  0.06
#> 2 3-Feb      5     13.1  0.63
#> 3 3-Mar     25     14.2 NA   
#> 4 3-Apr     26     13.6 NA   
#> 5 3-May     27     12.8 NA   
#> 6 3-Jun     27     15.6 NA

Created on 2021-07-14 by the reprex package (v2.0.0)

Andy Eggers
  • 592
  • 2
  • 10