简体   繁体   English

在操作中使用字符串作为对象名称

[英]Use character string as object name in operations

I am all too inexperienced in programming generally and R specifically so please forgive me if what I have is bad coding. 我一般对R和R编程都缺乏经验,所以如果我的代码不好,请原谅我。

The problem I am trying to solve is to load many separate csv files into R, tidy up the input a bit, perform a few operations on the resulting objects and eventually plot the results of those operations. 我要解决的问题是将许多单独的csv文件加载到R中,整理一下输入内容,对所得对象执行一些操作,并最终绘制出这些操作的结果。 The way I have tried to solve it is to use a vector of strings which echoes the object names to call the objects in question. 我尝试解决的方法是使用字符串向量,该向量回显对象名称以调用有问题的对象。 This does not work. 这是行不通的。

Below is a bit of code which after loading the data does not work. 下面是一些代码,这些代码在加载数据后不起作用。

files=list.files('foldername',pattern="*.csv",full.names=F) #Make a list of files
filen=str_extract(files, '.*(?=\\.csv)') #Pretty the file names for object names

for (i in 1:length(files)){
   assign(paste(filen[i]),read.csv(paste(files[i]))) #Load the files
   as.object(filen[i])=as.object(filen[i])[,order(names(ATCN_21))] # pseudocode line
   as.object(filen[i])=operation(as.object(filen[i]),parameter 1, parameter 2, etc) #More pseudocode
}

where operation may be a plot command or an arbitrary function such as rbind, colnames, whatever you may fancy. 其中的操作可以是绘图命令,也可以是任意功能,例如rbind,colnames,无论您喜欢什么。

In other words: I need some way to use string i in vector filen exactly as if it were an object name. 换句话说: 我需要某种方法在向量filen中使用字符串i ,就像它是对象名称一样。 How can I do this? 我怎样才能做到这一点?

The solution: Lists. 解决方案:列表。 (Thank you, Pierre) (谢谢皮埃尔)

files=list.files('foldername',pattern="\\.csv$",full.names=F) #Make a list of files
filen=str_extract(files, '.*(?=\\.csv)') #Pretty the file names for object names

list=lst()


for (i in 1:length(files)){
   lst[[i]]=read.csv(paste(files[i]))#Load the files
   names(lst)[i]<-filen[i] #Name the entries
   lst[[i]]=lst[[i]][,order(names(lst[[i]]))]

   lst[[i]]=operation(foo)
}

Thank you for helping a clueless n00b. 感谢您帮助无知的n00b。

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

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