简体   繁体   中英

How to create a print value from output of function?

I have this dataframe:

df <- data.frame(ID=rep(33,5),
                 Number=1:5,
                 Time=c(2.00,1.98,0.82,2.12,2.53),
                 Distance=c(870,859,305,651,502))

I wanted to filter it by Time so I used this code(thanks to a previous post):

getHLN <- function(df, ID) {
  df %>%
    filter (ID ==id & (Number %in% 1:3 & (Time < 0.90))|
           (ID == id & (Number %in% 4:5 & (Time > 2.10))))
}

Which now gives this output:

  ID Number Time Distance
1 33      3 0.82      305
2 33      4 2.12      651
3 33      5 2.53      502

I'm wondering if I would be able to create or edit my current function to produce an output that has an output printing -3, +4, +5 instead to differentiate between less than and greater more easily?

If we need a character column, then use mutate to modify the 'Number' column

getHLN <- function(df, id) {
 df %>%
    filter(ID ==id & (Number %in% 1:3 & (Time < 0.90))|
       (ID == id & (Number %in% 4:5 & (Time > 2.10)))) %>%
    mutate(Number = ifelse(Time < 0.90, paste0("-", Number), paste0("+", Number)))

 }

getHLN(df, 33)
#   ID Number Time Distance
#1 33     -3 0.82      305
#2 33     +4 2.12      651
#3 33     +5 2.53      502

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