I have a simple data frame:
dataframe_initial <- data.frame(
Pot = c("1", "1", "2", "2", "3", "3"),
Mass = c("25","37","51","42","34","29")
)
And I want this:
dataframe_wanted <- data.frame(
Pot = c("1", "1", "2", "2", "3", "3"),
Mass = c("25","37","51","42","34","29"),
Mass_reverse = c("37","25","42","51","29","34"),
Mass_diff = c("-12","12","9","-9","5","-5")
)
I apologize if this is quite obvious, but I took a long look on the web, without convincing help. To put it in words, I want to:
1-Add a new column with existing data (here mass), but reserved with conditions on a third column (Pot)
2- Add a new column with the differences between two values in the same initial column (Mass), but with conditions on a third column (Pot)
Many thanks in advance,
CodePudding user response:
Do a rev
erse after grouping and then get the difference (-
)
library(dplyr)
dataframe_initial %>%
type.convert(as.is = TRUE) %>% # // automatically change the class
group_by(Pot) %>%
mutate(Mass_reverse = rev(Mass),
Mass_diff = Mass - Mass_reverse) %>%
ungroup
-output
# A tibble: 6 × 4
Pot Mass Mass_reverse Mass_diff
<int> <int> <int> <int>
1 1 25 37 -12
2 1 37 25 12
3 2 51 42 9
4 2 42 51 -9
5 3 34 29 5
6 3 29 34 -5
NOTE: quoting the values make them character
class.