繁体   English   中英

我如何在R中将函数名称与for一起使用

[英]How I can use the function names with for in R

我的R代码有一点问题。 我不知道在哪里,但我犯了一个错误。 问题是:

我有许多文件excel,它们具有相同的列名。 我想更改矩阵的标题以及其他标题。

这是五个文件。

AA <- read_excel("AA.xlsx") 
BB <- read_excel("BB.xlsx")
CC <- read_excel("CC.xlsx")
DD <- read_excel("DD.xlsx")
EE <- read_excel("EE.xlsx")

head(AA) #the matrix is the same for the other file. DATA Open Max Min Close VAR % CLOSE VOLUME <dttm> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> 1 2004-07-07 00:00:00 3.73 3.79 3.6 3.70 0 21810440 2 2004-07-08 00:00:00 3.7 3.71 3.47 3.65 -1.43 7226890 3 2004-07-09 00:00:00 3.61 3.65 3.56 3.65 0 3754407 4 2004-07-12 00:00:00 3.64 3.65 3.59 3.63 -0.55 850667 5 2004-07-13 00:00:00 3.63 3.63 3.58 3.59 -1.16 777508 6 2004-07-14 00:00:00 3.54 3.59 3.47 3.5 -2.45 1931765

为了快速更改标题,我决定使用此代码。

t <- list(AA, BB, CC, DD, EE)
for (i in t ) {
names(i) <- c("DATA", "OPE", "MAX", "MIN", "CLO", "VAR%", "VOL")
} #R dosen't give any type of error!


head(AA) #the data are the same, as the for dosen't exits. 

我哪里错了?

提前非常感谢您。

弗朗切斯科

我们可以通过lapply做到这lapply 使用mget获取list的数据集,遍历list ,将列名称设置为名称向量('nm1),并使用list2env修改全局环境中的对象

nm1 <- c("DATA", "OPE", "MAX", "MIN", "CLO", "VAR%", "VOL")
lst <- lapply(mget(nm2), setNames, nm1)
list2env(lst, envir = .GlobalEnv)

或使用for循环,遍历对象名称的字符串,并将列名称assign全局环境中的对象

for(nm in nm2) assign(nm, `names<-`(get(nm), nm1))

或使用tidyverse

library(tidyverse)
mget(nm2) %>% 
    map(set_names, nm1) %>%
    list2env(., envir = .GlobalEnv)

数据

AA <- mtcars[1:7]
BB <- mtcars[1:7]
CC <- mtcars[1:7]
DD <- mtcars[1:7]
EE <- mtcars[1:7]
nm2 <- strrep(LETTERS[1:5], 2)

我试图解释为什么您的代码不起作用。 在列表tAA的地址(t [[1]])与全局环境中的AA相同。 在for循环中, i最初是与全局环境中的data.frame AA相同的副本。 当您使用names(i) <-更改inames(i) <- ,会将data.frame i复制两次。 最后,您正在更改全局环境中的新data.frame i而不是原始data.frame AA的名称。

这是一个说明我的意思的示例( tracemem “标记一个对象,以便在内部代码复制该对象时打印一条消息。”):

tracemem(mtcars)
# [1] "<0x1095b2150>"
tracemem(iris)
# [1] "<0x10959a350>"

x <- list(mtcars, iris)

for(i in x){
    cat('-------\n')
    tracemem(i)
    names(i) <- paste(names(i), 'xx')
}
# -------
# tracemem[0x1095b2150 -> 0x10d678c00]: 
# tracemem[0x10d678c00 -> 0x10d678ca8]: 
# -------
# tracemem[0x10959a350 -> 0x10cb307b0]: 
# tracemem[0x10cb307b0 -> 0x10cb30818]:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM