【发布时间】: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 语句。我会建议一个数据框列表(请参阅下面的答案)或一个带有额外列的大型数据框用于您的项目编号。这一切都取决于您未来的分析要求。