I wish to change one of my column values relative to several columns under a condition. If columns y2010 to y2019 all have zeros, then the column slope_median
has a zero, otherwise, leave it as it is.
My expected output:
# A tibble: 6 x 13
id y2010 y2011 y2012 y2013 y2014 y2015 y2016 y2017 y2018 y2019 slope_median slope_sd
<dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 1 0 0 0 0 0 0 0 0 0 0 0 0
2 2 0.1 0 0.2 0.1 0 0.1 0 0 0 0 0.243 0.0676
3 3 0 0.3 0.3 0.2 0 0 0 0.1 0 0 0.212 0.0621
4 4 0 0 0 0 0 0 0 0 0 0.1 0.354 0.197
5 5 0 0.4 0 0 0 0 0 0 0 0 0.516 0.156
6 6 0 0 0 0 0 0 0 0 0 0 0 0
What I have tried:
data$slope_median ifelse(data[,2:11] >0, data$slope_median, 0)
and
when(tt[,2:11] >0, tt$slope_median)
neither work as expected.
reproducible code:
structure(list(id = c(1, 2, 3, 4, 5, 6), y2010 = c(0, 0.1, 0,
0, 0, 0), y2011 = c(0, 0, 0.3, 0, 0.4, 0), y2012 = c(0, 0.2,
0.3, 0, 0, 0), y2013 = c(0, 0.1, 0.2, 0, 0, 0), y2014 = c(0,
0, 0, 0, 0, 0), y2015 = c(0, 0.1, 0, 0, 0, 0), y2016 = c(0, 0,
0, 0, 0, 0), y2017 = c(0, 0, 0.1, 0, 0, 0), y2018 = c(0, 0, 0,
0, 0, 0), y2019 = c(0, 0, 0, 0.1, 0, 0), slope_median = c(0.474975518924233,
0.243454068541322, 0.212280103001613, 0.35383141799496, 0.516334127008962,
0.356965572683185), slope_sd = c(0.111160151030104, 0.0675751738339188,
0.0621022972843367, 0.196846417185408, 0.155712046330888, 0.102009447727955
)), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))
Aucun commentaire:
Enregistrer un commentaire