使用make.names或在工作环境中重命名OBEJCT时,用下划线替换点

发布于 2025-01-20 19:39:58 字数 562 浏览 0 评论 0原文

我正在使用 this (我知道,我知道)解决方案在上传文件夹时自动命名Excel文件。

temp = list.files(pattern="*.csv")
list2env(
  lapply(setNames(temp, make.names(gsub("*.csv$", "", temp))), 
         read.csv), envir = .GlobalEnv)

现在,make.names使用制作正确的名称,而我宁愿使用_。动态将点更改为强调的最佳方法是什么?

我尝试做类似lapply(ls(),gsub(“。”,“ _”))之类的事情,但这似乎不起作用。 我也希望在list2env中进行此操作,但我会选择单独的行。

I am using this (ill advised, I know) solution to automatically name Excel files when uploading a folder.

temp = list.files(pattern="*.csv")
list2env(
  lapply(setNames(temp, make.names(gsub("*.csv
quot;, "", temp))), 
         read.csv), envir = .GlobalEnv)

Now, make.names uses . to make correct names, while I would rather use _. What would be the best way to dynamically change the dots to underscores?

I tried to do something like lapply(ls(),gsub(".", "_")), but that does not seem to work.
I would also prefer to do it within list2env, but I'll settle for a separate line.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

朕就是辣么酷 2025-01-27 19:39:58

问题可能是使用 "." ,它在正则表达式中匹配每个字符。如果要匹配字符串中的 .,则必须使用 "\\." 对其进行转义。

就我个人而言,当您可以使用一个简单的函数使代码更清晰、更易于理解时,我不喜欢将所有代码都放在一行中。

# Example data
write.csv(mtcars, "mt cars.csv")
write.csv(mtcars, "mt car s.csv")

temp = list.files(pattern="*.csv")

make_names <- function(x) {
  gsub("\\.", "_", make.names(gsub("*.csv$", "", x)))
}
names(temp) <- make_names(temp)

list2env(lapply(temp, read.csv), envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

ls()
#> [1] "make_names" "mt_car_s"   "mt_cars"    "temp"

The issue is probably that use you use "." which in a regex matches every character. If you want to match a . in a string you have to escape it using use "\\.".

Personally I don't like it to wrangle all code in one line when you could use a simple function to make the code cleaner and more understandable.

# Example data
write.csv(mtcars, "mt cars.csv")
write.csv(mtcars, "mt car s.csv")

temp = list.files(pattern="*.csv")

make_names <- function(x) {
  gsub("\\.", "_", make.names(gsub("*.csv
quot;, "", x)))
}
names(temp) <- make_names(temp)

list2env(lapply(temp, read.csv), envir = .GlobalEnv)
#> <environment: R_GlobalEnv>

ls()
#> [1] "make_names" "mt_car_s"   "mt_cars"    "temp"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文