使用for循环进行赋值

时间:2017-05-19 19:03:24

标签: r for-loop assign

我有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


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

    }

1 个答案:

答案 0 :(得分:0)

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

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

此提示也可用于第二次循环。