我正在尝试将一个具有两列的excel工作表放入数据框中,
列A包含商店名称 B列包含这些商店的URL。
我想选择A列并使其成为可单击的超链接,因此它是通向商店网站的超链接,而不是纯文本。
我尝试使用openxlsx软件包生成正确的输出。
我尝试使用以下代码段。
x <- c("https://www.google.com", "https://www.google.com.au")
names(x) <- c("google", "google Aus")
class(x) <- "hyperlink"
writeData(wb, sheet = 1, x = x, startCol = 10)
来自类似性质的帖子。 https://stackoverflow.com/a/48973469/11958444
但是我的问题是当我替换代码的适当部分时,例如:
x <- df$b
names(x) <- df$a
class(x) <- "hyperlink"
writeData(wb, sheet = 1, x = x, startCol = 10)
不是给我一列以商店名称作为输出的超链接,而是给我整个URL作为输出。我的代码中缺少什么吗?
我得到的输出具有可单击的链接,但是它没有打印出带有名称的URL,而是仅打印出URL。
答案 0 :(得分:1)
使用openxlsx
的方法:
library(openxlsx)
library(dplyr)
# create sample data
df <- data.frame(
site_name = c("Zero Hedge", "Free Software Foundation"),
site_url = c("https://www.zerohedge.com", "https://www.fsf.org")
)
# add new column that manually constructs Excel hyperlink formula
# note backslash is required for quotes to appear in Excel
df <- df %>%
mutate(
excel_link = paste0(
"HYPERLINK(\"",
site_url,
"\", \"",
site_name,
"\")"
)
)
# specify column as formula per openxlsx::writeFormula option #2
class(df$excel_link) <- "formula"
# create and write workbook
wb <- createWorkbook()
addWorksheet(wb, "df_sheet")
writeData(wb, "df_sheet", df)
saveWorkbook(wb, "wb.xlsx", overwrite = TRUE)