简体   繁体   English

使用R中的循环项动态创建数据帧

[英]Creating data frames dynamically using items of loop in R

I have a for loop as 我有一个for循环

for(i in c("a","b","c","d"))
{
    as.name(paste("df",i,sep=""))= mydataframe
}

mydataframe is a data frame and I want to create data frames dfa , dfb , dfc and dfd using this loop. mydataframe是一个数据帧,我想使用此循环创建数据帧dfadfbdfcdfd

The as.name(paste("df",i,sep="")) does not work here. as.name(paste("df",i,sep=""))在这里不起作用。 I do not want to create a list that has the 4 data frames. 我不想创建具有4个数据框的列表。

Can I directly create 4 data frames from this loop? 我可以从该循环中直接创建4个数据帧吗?

You can do this using assign . 您可以使用assign执行此操作。 Although in general, you are better off using lists. 尽管通常来说,最好使用列表。

Using your example: 使用您的示例:

for(i in letters[1:4]){
  assign(paste0("df", i), mydataframe)
}

Note that this will simply create the same object 4 times, unless you change what mydataframe is inside the loop. 请注意,除非您更改循环中的mydataframe ,否则这只会简单地创建同一对象4次。

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

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