通过for循环和函数附加到数据框

时间:2018-11-09 10:33:32

标签: r function loops append rbind

当我最后运行带有另存为csv的代码时,一切都可以正常运行。这意味着我要按国家/地区筛选数据集,并进行一些延续并将其另存为国家/地区文件。 当我尝试绑定数据集时,我什么也没收到。我尝试了不同的解决方案,但发现没有任何效果。显然我不明白为什么我不能这样做。

代码:

library(dplyr)
library(readxl)

setwd("Z:/Reporting_Private/Tableau")
dataupl <- read_excel("Analysis Map_Tableau - Ready.xlsm", sheet = "Data")

df = dataupl

#select right columns 
df = df[,1:6]
colnames(df)=c("Office", "Employee","Territiry","Sales","Leads","Act")

#change n/a to zero
df[is.na(df)]=0

countries = df %>% select(Office) %>% distinct()
countries = as.data.frame(countries)

engine <- function(input){

  df = df %>% filter(Office==input)

  SCALESALES = scale(df$Sales)
  SCALELEADS= scale(df$Leads)
  SCALEACT= scale(df$Act)

  df = df %>% mutate(SCALESALES = SCALESALES, SCALELEADS = SCALELEADS, SCALEACT = SCALEACT)

  df$SLegend = ave(df$Sales, df$SalesLegend, FUN = min)   
  df$SLegend = ifelse(df$SLegend>0, df$SLegend,0)
  df$LLegend = ave(df$Leads, df$LeadsLegend, FUN = min)   
  df$ALegend = ave(df$Act, df$ActLegend, FUN = min)   


  #write.csv(final, file = paste0(input,".csv"))
  dftotal = data.frame()
  dftotal = rbind(dftotal,df)
}

for (i in 1:nrow(countries)){

  input = countries[i,]

  engine(input)

}

1 个答案:

答案 0 :(得分:0)

似乎您可以拆分数据框L <- split(df, df$Office),然后lapply(L, ...)而不是write.csv(...),而必须返回数据框:return(df)
所以,像这样:

engine <- function(dfi) {

  SCALESALES = scale(dfi$Sales)
  SCALELEADS = scale(dfi$Leads)
  SCALEACT   = scale(dfi$Act)

  dfi = dfi %>% mutate(SCALESALES = SCALESALES, SCALELEADS = SCALELEADS, SCALEACT = SCALEACT)

  dfi$SLegend = ave(dfi$Sales, dfi$SalesLegend, FUN = min)   
  dfi$SLegend = ifelse(dfi$SLegend>0, dfi$SLegend, 0)
  dfi$LLegend = ave(dfi$Leads, dfi$LeadsLegend, FUN = min)   
  dfi$ALegend = ave(dfi$Act, dfi$ActLegend, FUN = min)   

  return(dfi)
}

L    <- split(df, df$Office)
Lnew <- lapply(L, engine)

dftotal <- Lnew[[1]]
for (i in 2:length(Lnew)) dftotal <- rbind(dftotal, Lnew[[i]])