You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R中编写循环生成4个名称仅尾字符不同的数据表?

Hey there! I get what you're trying to do here—you want to create multiple data frame objects (tabDummy1 to tabDummy4) in a loop, but using paste0 directly on the left side of the assignment doesn't work because it just returns a string, not an actual object name. Let's go through a couple of ways to fix this:

Method 1: Use assign() to Create Named Objects

The assign() function is exactly what you need here—it lets you create an object in your environment using a string as its name. Here's how to adjust your code:

for(i in 1:4){
  # Generate the object name as a string
  obj_name <- paste0("tabDummy", i)
  # Assign your data frame to this named object
  assign(obj_name, data.frame(data[, c(1, i+1)], colnames(data)[i+1]))
}

After running this loop, you'll have tabDummy1, tabDummy2, tabDummy3, and tabDummy4 as separate data frames in your workspace.

While assign() works, a more idiomatic and cleaner approach in R is to store related data frames in a list instead of creating separate objects. This keeps your workspace organized, makes it easier to iterate over all your data frames later, and avoids cluttering your environment with dozens of similar-named objects.

Here's how to do it:

# Start with an empty list
tab_dummies_list <- list()

for(i in 1:4){
  # Assign each data frame to a named element in the list
  list_element_name <- paste0("tabDummy", i)
  tab_dummies_list[[list_element_name]] <- data.frame(data[, c(1, i+1)], colnames(data)[i+1])
}

To access individual data frames later, you can use:

  • tab_dummies_list$tabDummy1 (using the element name)
  • tab_dummies_list[[1]] (using the index position)

Plus, if you need to run the same operation on all your data frames (like filtering, summarizing), you can use functions like lapply() or purrr::map() to process the entire list in one go—way more efficient than handling each object separately!


内容的提问来源于stack exchange,提问作者gustavomoty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:10:51