【问题标题】:assignment with for loops用 for 循环赋值
【发布时间】:2017-10-20 00:16:37
【问题描述】:

我有 4 件物品。每个项目都有随机数量的位置,每个位置都有数据。我现在拥有的代码遍历位置并创建位置数据的数据框。然后我想获取该位置数据,将其放入相应项目的数据框中,然后移动到该项目的下一个位置,该位置将被添加到项目数据框中,依此类推,直到该项目的所有位置项目已添加到项目数据框中。我希望它然后移动到下一项并为单独命名的数据框重复该过程。例如,项目 1 的数据框应命名为 item1,项目 2 的数据框应命名为 item2 等。我尝试使用 assign 和 paste0 函数来完成此操作,但 paste0 创建了一个字符串,而 assign 函数无法识别我想将数据分配给数据框,而不是字符串。示例代码发布在下面,非常感谢您提供的任何帮助!

  for (p in 1:4) # 1-4 because there are 4 items
  {
    #Initialize the item data frame
    assign(paste0("item",p),data.frame(item_no=character(), x=integer(), y=integer(), data_val=integer()))

      #Loop through all locations for this item ID
      num_locations = sample(1:9,1) #Number of locations
      for (i in 1:(num_locations)){ #Loop through each location

        #Access data for current location (pulls from a database in actual code)

        ##################################################
        item_no <- p
        x <- sample(-3:3,1)
        y <- sample(-3:3,1)
        data_val <- sample(0:100,1)
        ##################################################

        #################DATA FRAME######################
        assign(paste0("location_data",i),data.frame(item_no, x, y, data_val))
        assign(paste0("item",p), data.frame(rbind(paste0("item", p), paste0("location_data", p))))


        #paste0 creates a string and therefore is not recognized that I want to call the data within itemp or location_datap
        #rbind needed because the loop through impact locations for a single item requries initialization of an empty data frame
        #for the first time through the location loop, the empty itemp data frame is overwritten by the location_datap data frame and supplemented each location thereafter


        ################################################
      }

    }

【问题讨论】:

  • 您的问题不是很清楚,有更简单的方法可以解决您的问题。通常不建议使用 assign 语句。我会建议一个数据框列表(请参阅下面的答案)或一个带有额外列的大型数据框用于您的项目编号。这一切都取决于您未来的分析要求。

标签: r for-loop assign


【解决方案1】:

我认为使用列表代替assign 函数是个好主意。例如:

items <- list()
for (p in 1:4) {
    items[[p]] <- data.frame(...)
    ...
    items[[p]] <- rbind(items[[p]], ...)
}

此技巧也可用于第二个循环。

【讨论】:

    猜你喜欢
    • 2016-01-17
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 2016-09-24
    • 2021-12-17
    • 2023-03-28
    相关资源
    最近更新 更多