I try to make some calculations with the following dataset:
dataset <- data.frame(specimen = c("NIA","NIA","NIA","MAT","MAT"),
brakg = c(9.4,0,0,7.8,0),
cebkg = c(0,2.3,3.1,0,2.4),
rotkg = c(0,1,1.1,0,1.2),
stringsAsFactors = FALSE)
specimen brakg cebkg rotkg
1 NIA 9.4 0.0 0.0
2 NIA 0.0 2.3 1.0
3 NIA 0.0 3.1 1.1
4 MAT 7.8 0.0 0.0
5 MAT 0.0 2.4 1.2
I want to have the brakg variable duplicated, the variables cebkg and rotkg available and a calculation from brakg - sum(cebkg) and brakg/sum(rotkg). This should be the result:
specimen list value
NIA Init 9.4
NIA Eval 9.4
NIA Ceb 2.3
NIA Ceb 3.1
NIA Rot 1.0
NIA Rot 1.1
NIA DiffA 4.0
NIA RateB 4.48
MAT Init 7.8
MAT Eval 7.8
MAT Ceb 2.4
MAT Rot 1.2
MAT DiffA 5.4
MAT RateB 6.5
I have tried (without success) this code:
spds <- split(dataset, dataset$specimen)
# Splitting the dataset to make an evaluation per specimen
res <- lapply(spds, function(DF){
i <- which(DF[['brakg']] != 0)
j <- which(DF[['cebkg']] != 0)
k <- which(DF[['rotkg']] != 0)
tmp <- rbind(DF[rep(i, 2), ], DF[j, ], DF[k, ])
# So I can stack the brakg value repetition... after that null ideas
})
Please, any help will be useful, even in base R or Tidyverse (I don't know if tidy functions can output different number of vars). Thank you.
listandvalue. - Ronak ShahDiffA = 9.4 - (2.3+3.1) = 4.0andRateB = 9.4/(1.0+1.1) = 4.48. For MATDiffA = 7.8 - (2.4) = 5.4andRateB = 7.8 / (1.2) = 6.5- Manulist = c("Init","Eval",rep("Ceb", length(quantity of non zero cebkg) , rep("Rot", length(quantity of non zero rotkg), "DiffA","RateB")repeated for each specimen. - Manubrakgfor aspecimen? If yes, can you include that in the example? - Ronak Shahbrakgper specimen. By the way ifbrakgis non-zero, thencebkgandrotkgare 0. And viceversa, ifcbkgandrotkgare non-zero, thenbrakgis 0. - Manu