简体   繁体   中英

Filtering the column and creating a new column by grouping the data and selecting a min of a column

Business understanding: Fliter the data using

Dataset_z$DayCount <= Dataset_z$t & Dataset_z$DayCount >= Dataset_z$Total.LT

then create a new column in Dataset_z by following condition

group_by(Dataset_z$Source,Dataset_z$Plant, Dataset_z$Material) %>% 
mutate(Dataset_z$A =  min(NET.INV))

please help me

I created some sample data by doing:

library(dplyr)

Dataset_z  <- data.frame(Total.LT = sample(1:6,10,replace=T), 
                         DayCount = sample(1:10,10,replace=T), 
                         t = sample(1:6,10,replace=T), 
                         NET.INV = sample(1:20, 10, replace = T),
                         Source = sample(c("a", "b", "c", "d", "e"),10,replace=T),
                         Plant = sample(c("a", "b", "c", "d", "e"),10,replace=T), 
                         Material = sample(c("a", "b", "c", "d", "e"),10,replace=T), stringsAsFactors = F)

DataSet_z looks like:

       Total.LT DayCount t NET.INV Source Plant Material

    1         5        6 6      20      a     c        b
    2         3        2 6       9      b     c        b
    3         4        4 2       5      e     e        d
    4         3        3 2      12      a     c        a
    5         1        8 2       9      c     d        a
    6         2        2 2      16      c     b        d
    7         4        8 1      15      c     b        a
    8         3        5 6       6      d     a        e
    9         5        3 6      11      c     b        a
    10        4        5 5       1      c     e        c

Doing the filter and grouping you do not need to use the $ operator because dplyr attaches the columns using the %>% operator.

Dataset_z %>% filter(DayCount >= Total.LT & DayCount <= t) %>% group_by(Source, Plant, Material) %>% mutate(A = min(NET.INV))

This results in:

     Total.LT DayCount     t NET.INV Source Plant Material     A
     <int>    <int> <int>   <int> <chr>  <chr> <chr>    <dbl>
1        5        6     6      20 a      c     b           20
2        2        2     2      16 c      b     d           16
3        3        5     6       6 d      a     e            6
4        4        5     5       1 c      e     c            1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM