Home > Mobile >  Printing several outputs in a table in R
Printing several outputs in a table in R

Time:10-19

I am working with a dataframe in R like below:

df<-data.frame((
item=c("a","a","c","d"),
price_today=c(1,"",3,4,5),

And in column item, I have filtered and selected "a" and in column price_today and I have filter out blank value. So the df should be like the one below:

df<-data.frame((
item=c("a"),
price_today=c(1)

So now what I am trying to do here is to print out how many variables I have filtered out in column item and how many blank values I have removed and put the 2 print outputs into a table.

print(ncol(df))

message("number of row that has A is",df[df$item=="a",]

From here, may I ask how do I put the 2 printed outputs into a table?

Many thanks for your help.

CodePudding user response:

Here's a solution using dplyr:

library(dplyr)

df <- data.frame(
  item=c("a","a","c","d", "e"),
  price_today=c(1,NA,3,4,5))

filter_function <- function(data, col_value) {
  n_filtered <- data %>% 
    filter(item != {{col_value}}) %>% 
    nrow()
  
  n_na <- data %>% 
    filter(is.na(price_today) & item != {{col_value}}) %>% 
    nrow()
  
  df_filtered <- df %>% 
    filter(item == {{col_value}} & !is.na(price_today))
  
  print(paste0('filtered ', n_filtered, ' rows where item != `', col_value, '` and ', n_na, ' rows that are NA'))
  
  return(df_filtered)
  
}

filter_function(df, 'a')
#> [1] "filtered 3 rows where item != `a` and 0 rows that are NA"
#>   item price_today
#> 1    a           1
  • Related