R函数限制列表元素名称的字符?

R function to limit characters of list element name?

我有一个元素列表。我想将此列表导出为 excel 文件,每个元素在同一 excel 文件中导出为单独的 sheet。 Excel 对 sheet 个名称有 31 个字符的限制。因此下面的导出将不起作用。

有没有办法使用函数来限制列表的字符数?比如把所有元素名都截掉30个字符?

employee <- c('John Doe','Peter Gynn','Jolie Hope')
salary <- c(21000, 23400, 26800)
startdate <- as.Date(c('2010-11-1','2008-3-25','2007-3-14'))

test1 <- list(employee, salary, startdate)

names(test1)[1] <- "employee of the month 2021 to 2022"
names(test1)[2] <- "salary of the best employees of test company"
names(test1)[3] <- "startdate"

write.xlsx(test1, file = "testlist.xlsx")

TIA

函数 substr 将起作用。

> substr("salary of the best employees of test company", start = 1, stop = 30)
[1] "salary of the best employees o"

在这种方法中,您可以通过定义停用词列表来节省 space,因此有更多 space 用于有意义的工作表名称。该示例包括在 test1 列表中更改您的姓名。要么原封不动,要么“半途而废”。

library(stringi)

# remove words without much meaning, add what you like
stopwords <- c("of", "the", "to")

names(test1) <- unlist(lapply(names(test1), function (x){
  x <- stri_extract_all_words(x)[[1]]
  x <- paste(x[!x %in% stopwords], collapse = " ")
  # strwrap(x, width = 30)[1] # keep words in tact
  substr(x, start = 1, stop = 30)
}))

names(test1)

# strwrap uncommented
# [1] "employee month 2021 2022"   "salary best employees test" "startdate"

# substr uncommented
# [1] "employee month 2021 2022"        "salary best employees test com" "startdate" 

# compare that to the outcome without removing stopwords
# [1] "employee of the month 2021 to " "salary of the best employees o" "startdate"