dimanche 24 janvier 2021

Naming three ways to convert values from one column given values of another

I tend to get into the habitat of facing this question constantly when programming, and I'll usually have one-for-all approach, which I may find difficult applying it depending on the dataset I'm working on.

Providing me with three different alternatives, so that I can look back to this page would be extremely helpful.

Such an example is, given this dataset:

# A tibble: 15 x 4
# Groups:   id [3]
   id       y2010 y2019   pland
   <chr>    <int> <int>   <dbl>
 1 L1146796    16     4  0.156 
 2 L1146796    16     8  0.531 
 3 L1146796    16     9  0.0938
 4 L1146796    16    13  0.219 
 5 L452817      8     8 -0.0323
 6 L452817      9     9  0.0323
 7 L452817     12    12 -0.0968
 8 L452817     13    13  0     
 9 L452817     14    14  0.0968
10 L910180      0    17 -0.438 
11 L910180      8    17 -0.344 
12 L910180      9    17 -0.0312
13 L910180     10    17 -0.0312
14 L910180     11    17 -0.0938
15 L910180     13    17 -0.0625

How do I convert only those values in pland that match the value 17 in y2019, from positive to negative values, and making this change in the column pland without creating a new one. Whilst changing those that are positive relative to 16 in y2010 into negative.

What are three different approaches towards this?

I've thought of using:

ifelse(j$pland[j$y2019 == 17], abs(j$pland), -j$pland)

#0.03225806 0.03225806 0.09677419 0.00000000 0.09677419 0.43750000

Although it only returns the vectors.

Reproducible code:

structure(list(id = c("L1146796", "L1146796", "L1146796", "L1146796", 
"L452817", "L452817", "L452817", "L452817", "L452817", "L910180", 
"L910180", "L910180", "L910180", "L910180", "L910180"), y2010 = c(16L, 
16L, 16L, 16L, 8L, 9L, 12L, 13L, 14L, 0L, 8L, 9L, 10L, 11L, 13L
), y2019 = c(4L, 8L, 9L, 13L, 8L, 9L, 12L, 13L, 14L, 17L, 17L, 
17L, 17L, 17L, 17L), pland = c(0.15625, 0.53125, 0.09375, 0.21875, 
-0.032258064516129, 0.0322580645161291, -0.096774193548387, 0, 
0.0967741935483869, -0.4375, -0.34375, -0.03125, -0.03125, -0.09375, 
-0.0625)), row.names = c(NA, -15L), groups = structure(list(id = c("L1146796", 
"L452817", "L910180"), .rows = structure(list(1:4, 5:9, 10:15), ptype = integer(0), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"), .drop = TRUE), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"))

Aucun commentaire:

Enregistrer un commentaire