如何在r-markdown pdf中将数据帧类别描述为部分和内容


df
Id  Section       Comment
------------------------------------------------------------
1   Product A   this is the general comment for product A
2   Product A   this is the general comment for product A
3   Product A   this is the general comment for product A
4   Product B   this is the general comment for product B
5   Product B   this is the general comment for product B
8   Product C   this is the general comment for product C
9   Product C   this is the general comment for product C
10  Product C   this is the general comment for product C

上面的一个是我的数据帧。我想找一些类似的输出

expected output:
------------------
Product A
this is the general comment for product A
this is the general comment for product A
Product B
this is the general comment for product B
this is the general comment for product B

如果我循环遍历每一行,我将以这种方式获得section and comment section and comment

我试着使用基于部分的索引,如下面的代码

分枝杆菌

section_df<-df%>%select("Section")%>% dplyr::mutate(r_number = row_number()) %>%
group_by(`Section`) %>%
dplyr::summarise(index = min(r_number))
section_df<-section_df[order(section_df$index),]
for(i in 1:nrow(df)){
if(section_df$index[i] == i){

cat(df$Section[i])
cat(df$Comment[i])
}else{
cat(df$Comment[i])
}

}
section_df<-section_df[complete.cases(section_df), ]
for(i in 1:nrow(df)){

if(i %in% section_df$index){
print(df$Section[i])
}
else{
print(df$Comment[i])
}
}

最新更新