Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
903 views
in Technique[技术] by (71.8m points)

filter - How to create another table in R to calculate the difference?

I have a set of data frame as below:

ID Parameter value
123-01 a1 x
123-02 a1 x
123-01 b3 x
123-02 b3 x
124-01 a1 x
125-01 a1 x
126-01 a1 x
124-01 b3 x
125-01 b3 x
126-01 b3 x
question from:https://stackoverflow.com/questions/65905769/how-to-create-another-table-in-r-to-calculate-the-difference

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

try to do it this way

library(tidyverse)
df <- read.table(text = "ID    Parameter value
123-01  a1  10
123-02  a1  10
123-01  b3  10
123-02  b3  10
124-01  a1  10
125-01  a1  10
126-01  a1  10
124-01  b3  10
125-01  b3  10
126-01  b3  10", header = T)

df %>% 
  arrange(Parameter, ID) %>% 
  separate(ID, into = c("id_grp", "n"), sep = "-", remove = F) %>% 
  group_by(Parameter, id_grp) %>% 
  mutate(diff_value = c(NA, diff(value))) %>% 
  select(-c(id_grp, n))
#> Adding missing grouping variables: `id_grp`
#> # A tibble: 10 x 5
#> # Groups:   Parameter, id_grp [8]
#>    id_grp ID     Parameter value diff_value
#>    <chr>  <chr>  <chr>     <int>      <int>
#>  1 123    123-01 a1           10         NA
#>  2 123    123-02 a1           10          0
#>  3 124    124-01 a1           10         NA
#>  4 125    125-01 a1           10         NA
#>  5 126    126-01 a1           10         NA
#>  6 123    123-01 b3           10         NA
#>  7 123    123-02 b3           10          0
#>  8 124    124-01 b3           10         NA
#>  9 125    125-01 b3           10         NA
#> 10 126    126-01 b3           10         NA

Created on 2021-01-26 by the reprex package (v0.3.0)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...