Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
702 views
in Technique[技术] by (71.8m points)

caption - Table and Figure cross-reference officer R

I would like to be able to cross-reference a table or figure in a word document using the officer R package.

I have come across these materials so far but they do not seem to have a solution: https://davidgohel.github.io/officer/articles/word.html#table-and-image-captions and a similar question add caption to flextable in docx

In both of these I can only insert a caption as a level 2 header and not a true table caption.

What I want to be able to do in Word is Insert -> Cross-reference and go to Reference type: Table and see my caption there. Right now I can only see the caption under Numbered item.

Does this functionality exist in officer or anywhere else?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In word, the table numbers use the { SEQ \@ arabic } pattern, but references to them use { REF bookmark h }. We can use this to make new code which can reference a SEQ field.

code:

ft <- regulartable(head(iris)) # create flextable
str <- paste0(' REF ft \h ')  # create string to be used as reference to future bookmark

doc <- read_docx() %>%
  body_add_par('This is my caption' , style = 'Normal') %>% # add caption
  slip_in_seqfield(str = "SEQ Table \@ arabic",           
                   style = 'Default Paragraph Font', 
                   pos = "before") %>% # add number for table
  body_bookmark('ft') %>%   # add bookmark on the number
  slip_in_text("Table ", 
               style = 'Default Paragraph Font', 
               pos = "before") %>% # add the word 'table'
  body_add_flextable(value = ft, align = 'left') %>% # add flextable
  body_add_break() %>%  # insert a break (optional)
  slip_in_text('As you can see in Table', 
               style = 'Default Paragraph Font', 
               pos = 'after') %>% # add the text you want before the table reference
  slip_in_seqfield(str = str,  
                   style = 'Default Paragraph Font', 
                   pos = 'after') %>% # add the reference to the table you just added
  slip_in_text(', there are a lot of iris flowers.', 
               style = 'Default Paragraph Font', 
               pos = 'after') %>% # add the rest of the text 
  print('Iris_test.docx') # print

Hope this helps :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...