在R中打印表格中的几个输出



我正在使用R中的数据帧,如下所示:

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

在列项目中,我过滤并选择了";a";在price_today列中,我过滤掉了空白值。所以df应该像下面这样:

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

所以现在我要做的是打印出我在列项目中过滤掉的变量数量和删除的空白值数量,并将两个打印输出放入一个表中。

打印(ncol(df((

消息("具有A的行的数目是",df[df$item=="A",]

在这里,我可以问一下如何将2个打印输出放入表格中吗?

非常感谢你的帮助。

以下是使用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

相关内容

最新更新