Create hyperlink in table and adjust column to wra

2019-08-03 04:41发布

问题:

I am trying to create hyperlinks inside a table and also adjust columns to wrap text and generate pdf.

Ex table:

variable<-"testing a long column to wrap testing a long column to wrap "
col1<-"\href{https://www.google.co.uk/}{click here}"
col2<-"[click here](https://www.google.co.uk/)"
col3<-"[click here](https://www.google.co.uk/)"
col4<-"[click here](https://www.google.co.uk/)"
col5<-"[click here](https://www.google.co.uk/)"
test<-data.frame(variable,col1,col2,col3,col4,col5)

When I tried the following it gives the hyperlinks correctly but does not adjust column width

library(kableExtra)
knitr::kable(test,row.names=FALSE) %>%
  column_spec(1, width = "5cm")

But when I tried with including format ='latex' then hyperlinks does not work but column width and wrap texts

library(kableExtra)
knitr::kable(test,format ='latex' ,row.names=FALSE) %>%
  column_spec(1, width = "5cm")

Please help me to add hyperlink and also to adjust column width in Rmarkdown.

回答1:

kableExtra only works when kable generates raw HTML/PDF codes. That's why when you don't specify format, that column_spec is not working.

After you specified the format, this problem turned into a "How to put links in kable (latex)" question. In fact, you are already very close to the answer. The point is that you have to set escape as F in kable so it can keep the LaTeX code as is. Also you have to double escape that backslash in col1 as it's a "R thing".

variable<-"testing a long column to wrap testing a long column to wrap "
col1<-"\\href{https://www.google.co.uk/}{click here}"
col2<-"\\href{https://www.google.co.uk/}{click here}"
col3<-"\\href{https://www.google.co.uk/}{click here}"
col4<-"\\href{https://www.google.co.uk/}{click here}"
col5<-"\\href{https://www.google.co.uk/}{click here}"
test<-data.frame(variable,col1,col2,col3,col4,col5)

knitr::kable(test,format ='latex',row.names=FALSE, escape = F) %>%
  column_spec(1, width = "5cm")