【问题标题】:Modifying an object referenced by "get()" in R修改 R 中“get()”引用的对象
【发布时间】:2021-09-18 21:39:36
【问题描述】:

如果之前有人问过这个问题,我们深表歉意。这是我对 R 的理解的极限,所以我什至不确定用于表达查询的正确语言(因此,我无法识别重复的问题)。

在我的环境中,我有未知数量的对象(数据框),每个对象都有未知数量的列,这些列具有有意义的名称但带有无意义的结尾,这使得引用它们变得困难。列名的有意义部分通常后跟一个双句点和一些进一步的文本。我想自动查找和删除无意义的后缀。我要修改的所有对象的名称中都有“.dat”。这是我尝试的一个例子:

# create some objects in my environment
a <- "a string, not of interest to me"
b.dat <- data.frame(col1 = 1:2, col2..gibberish = 3:4)
c.dat <- data.frame(col1..some.text = 5:6, col2 = 7:8) 

# find the dataframes that I want to manipulate
dfs <- ls(pattern = ".dat")

# loop through the objects in question, finding and changing the problematic column names
colrename <- lapply(dfs, function(df){
  
  # get the relevant dataframe
  dat <- get(df)
  
  # find its column names
  nms <- names(dat)
  
  # find the column names with the problematic ".." suffixes
  problem.cols <- grep("\\.\\.",nms)
  
  # pull out the meaningful first parts of each problematic name
  parts <- strsplit(nms[problem.cols],"\\.\\.")
  parts <- sapply(parts, function(x) x[1])
  
  # and, the bit that doesn't work: change the problematic column names to their shorter alternatives
  names(get(df))[problem.cols] <<- parts
  return(0)
})

如果我逐行运行,它会执行我想要的所有操作,包括 names(get(df))[problem.cols],它知道这是列的名称在我试图改变的数据框中。但是,它不会为其分配更改后的名称,从而产生错误消息:Error in get(*tmp*) : invalid first argument

我愿意采用替代方法来实现我想要的终点。但是,我也对为什么这不起作用以及如何更普遍地更改使用“get()”引用的对象很感兴趣。提前感谢您的任何建议 - 如果这太天真了,只是阅读它是在浪费您的时间,我们深表歉意。

FWIW,我可以看到与 this question 的相似之处,但我无法根据自己的需要调整答案。

【问题讨论】:

  • 将 get(df) 替换为 .GlobalEnv[[df]]。然而,这是一个糟糕的设计的结果。这些 data.frames 应该一起在一个列表中,而不是在全局环境中。
  • 谢谢@Roland!我同意你关于列表的观点(我想到如果它们在列表中,我的生活会更轻松)。然而,真正的数据帧是非常不同的,而且也是巨大的。它们的数量也可能不同。如果可以避免的话,我不想将它们结合起来。感谢您的语法建议!
  • 如果你真的需要 get 和 assign 你做错了或非常高级。列表只是指向内存中实际对象的指针。它几乎不需要额外的内存,但如果你想迭代对象,它会非常方便。
  • 啊,@Roland,这让人放心。因此,我想暂时设置列表并在完成后将其删除是没有问题的。但是(冒着任务蔓延的风险)当我不想单独命名对象时,我将如何创建对象列表?类似 (new.list
  • 我认为,@Roland,mget() 是我正在寻找的答案 - 但如果我错了,请随时纠正我。再次感谢您的建议。

标签: r dataframe get assign names


【解决方案1】:

实际上,我最终建立了使用“分配”功能的链接。这似乎有效(所以我把它贴在这里,以防它帮助其他人) - 但我仍然对替代解决方案感兴趣:

# loop through the objects in question, finding and changing the problematic column names
colrename <- lapply(dfs, function(df){
  
  # get the relevant dataframe
  dat <- get(df)
  
  # find its column names
  nms <- names(dat)
  
  # find the column names with the problematic ".." suffixes
  problem.cols <- grep("\\.\\.",nms)
  
  # pull out the meaningful first parts of each problematic name
  parts <- strsplit(nms[problem.cols],"\\.\\.")
  parts <- sapply(parts, function(x) x[1])
  
  # change the problematic column names to their shorter alternatives
  nms[problem.cols] <- parts
  names(dat) <- nms
  assign(df, dat, envir = .GlobalEnv)
  return(0)
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-28
    • 1970-01-01
    • 2018-06-29
    • 2012-01-29
    • 2014-12-19
    • 2023-03-14
    • 2021-09-02
    相关资源
    最近更新 更多