For循环只创建一个数据集

时间:2018-04-30 15:02:18

标签: r for-loop dataset

我希望你能帮助我。 我目前正在尝试使用for循环加载和创建多个数据集。该循环应该加载不同的数据集,总共62个类别。但是,它并没有真正用数字代替X,而只创建datasetX。

我希望我能够解释我的问题。这是我的代码:

##### Defining brands and START LOOP ####
for(X in c("8", "34", "35", "39", "44", "48", "49", "50", "51", "52", "53", "54", "55", "56", "120", "134", "138", "181", "182", "187", "190", "192", "199", "200", "205", "212", "215", "271", "274", "279", "329", "330", "331", "332", "333", "334", "335", "344", "345", "346", "349", "350", "351", "371", "372", "410", "411", "412", "413", "414", "418", "429", "443", "444", "455", "456", "527", "528", "529", "530", "534", "559")){

#Display
DisplayX <- read_excel("~/Master Studium/Thesis/IRI/displayOnly/DisplayOnly_Category8.xlsx")
DisplayX <- transpose(DisplayX)
DisplayX <- DisplayX[-c(1), ]
DisplayX$V1 <- NULL
DisplayX$Week <- as.matrix(c(1:208))

#sales
SalesX <- read_excel("~/Master Studium/Thesis/IRI/volumeSales/volumeSales_Category8.xlsx")
SalesX <- transpose(SalesX)
SalesX <- SalesX[-c(1), ]
SalesX$V1 <- NULL
SalesX$Week <- as.matrix(c(1:208))

#price
PriceX <- read_excel("~/Master Studium/Thesis/IRI/price/Price_Category8.xlsx")
PriceX <- transpose(PriceX)
PriceX <- PriceX[-c(1), ]
PriceX$V1 <- NULL
PriceX$Week <- as.matrix(c(1:208))

#advertising
AdvertisingX <- read_excel("~/Master Studium/Thesis/IRI/advertising/Advertising_Category8.xlsx")
AdvertisingX <- transpose(AdvertisingX)
AdvertisingX <- AdvertisingX[-c(1), ]
AdvertisingX$V1 <- NULL
AdvertisingX$Week <- as.matrix(c(1:208))

#importing brand 1 into a dataframe 
CategoryXa <- as.matrix(c(1:208))
CategoryXa <- as.data.frame(CategoryXa)
names(CategoryXa)[names(CategoryXa)=="V1"] <- "Week"
CategoryXa$Category <- X
CategoryXa$Brand <- 2
CategoryXa$Display <- DisplayX$V2
CategoryXa$Sales <- SalesX$V2
CategoryXa$Price <- PriceX$V2
CategoryXa$Advertising <- AdvertisingX$V2

#importing brand 2 into a dataframe 
CategoryXb <- as.matrix(c(1:208))
CategoryXb <- as.data.frame(CategoryXb)
names(CategoryXb)[names(CategoryXb)=="V1"] <- "Week"
CategoryXb$Category <- X
CategoryXb$Brand <- 3
CategoryXb$Display <- DisplayX$V3
CategoryXb$Sales <- SalesX$V3
CategoryXb$Price <- PriceX$V3
CategoryXb$Advertising <- AdvertisingX$V3

#importing brand 3 into a dataframe
CategoryXc <- as.matrix(c(1:208))
CategoryXc <- as.data.frame(CategoryXc)
names(CategoryXc)[names(CategoryXc)=="V1"] <- "Week"
CategoryXc$Category <- X
CategoryXc$Brand <- 4
CategoryXc$Display <- DisplayX$V4
CategoryXc$Sales <- SalesX$V4
CategoryXc$Price <- PriceX$V4
CategoryXc$Advertising <- AdvertisingX$V4

CategoryX <- rbind(CategoryXa, CategoryXb, CategoryXc) 
}

因此,我没有数据集Category8,Category34,Category35等,而只是以CategoryX结束。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

这是一个如何从循环内部定义新变量的简短示例:

for (i in 1:10) {
  assign(paste("newVar",i,sep=""), i, envir = .GlobalEnv)
}