我动态创建一个数据帧,我使用自定义名称来引用这些数据帧。但是,我可以成功地动态创建数据帧并单独添加信息,但是当我尝试向其中添加记录时手动进行操作,它将运行行动,但没有任何反应。我可以打开数据框,它显示为空
#Extract unique machines on the system
machines <- unique(wo_raw$MACHINE)
for(machine in machines){
#Check if the machine is present on current data frames or has a record
if(exists(machine) && is.data.frame(get(machine))){
#Machine already exists on the system
cat(machine," is a dataframe","\n")
netlbs <- subset(wo_raw,((wo_raw$TYPE =="T" & wo_raw$TYPE2=="E") | (wo_raw$TYPE == "T" & is.na(wo_raw$TYPE2))) & wo_raw$WEEK<=curWeek & wo_raw$MACHINE == machine & wo_raw$YEAR == curYear,select = NET_LBS)
scraplbs<- subset(wo_raw,((wo_raw$TYPE =="T" & wo_raw$TYPE2=="E") | (wo_raw$TYPE == "T" & is.na(wo_raw$TYPE2))) & wo_raw$WEEK<=curWeek & wo_raw$MACHINE == machine & wo_raw$YEAR == curYear,select = SCRAP_LBS)
if(is.data.frame(netlbs) && nrow(netlbs)!=0){
totalNet<- sum(netlbs)
totalScrap<- sum(scraplbs)
scrapRate <- percent(totalScrap/(sum(totalNet,totalScrap)),accuracy = 2)
tempDf<-data.frame(curYear,curMonth,curDay,curWeek,totalNet,totalScrap,scrapRate)
names(tempDf)<-c("year","month","day","week","net_lbs","scrap_lbs","scrap_rate")
cat("Total Net lbs for ",machine,": ",totalNet,"\n")
cat("Total Scrap lbs for ",machine,": ",totalScrap,"\n")
cat("Total Scrap Rate for ",machine,": ",scrapRate,"\n")
#machine<-rbind(get(machine),tempDf)
#assign(machine,rbind(machine,tempDf))
add_row(get(machine),year=curYear,
month=curMonth,
day=curDay,
week=curWeek,
net_lbs=totalNet,
scrap_lbs=totalScrap,
scrap_rate=scrapRate)
cat("added row \n")
}
#info<-c(curYear,curMonth,curDay,curWeek,netlbs)
#cat("Total Net lbs: ",netlbs,"\n")
#netlbs <-NULL
}else{
cat("Creating machine dataframe: ",machine,"\n")
#Create a dataframe labeled with machine name contining
#date information, net lbs,scrap lbs and scrap rate
assign(paste0(machine,""),data.frame(year=integer(),
month=integer(),
day=integer(),
week=integer(),
net_lbs=double(),
scrap_lbs=double(),
scrap_rate=integer()
)
)
#machine$year<-curYear
}
#machine<-NULL
}
我尝试过的所有功能都位于Stack Overflow上先前答案的注释行中。我确实使用过for,但是我认为那真的不可行,因为它将消耗大量资源,并且在处理各种数据类型时效果不佳。有人对发生的事情有想法吗,我没有错误可言。
答案 0 :(得分:-1)
我认为您的代码需要大量清理。确保在每个步骤中都自己知道要处理的内容。
一些提示:
curYear
。我知道应该是2019年,但是我需要输入很多内容才能解决问题,我不能只是复制粘贴。add_row
会做什么或应该做什么。所以我也不知道那是你的期望错了吗?cat
的内容,但是为什么会有netlbs <- subset(wo_raw,((wo_raw$TYPE =="T" & wo_raw$TYPE2=="E") | (wo_raw$TYPE == "T" & is.na(wo_raw$TYPE2))) & wo_raw$WEEK<=curWeek & wo_raw$MACHINE == machine & wo_raw$YEAR == curYear,select = NET_LBS)
这样的行?对于这个问题,只需使用subset(wo_raw, wo_raw$mach==machine, net)
之类的if (is.data.frame(netlbs)) {total=sum(netlbs)}
可能有效,但是在实际上只需要一列的情况下对data.frame求和会引起混淆。machine
不是data.frame,而是character
。 character
是另一个变量的 name ,它是一个data.frame。因此(注释),我看到了machine <- NULL
和machine$year
的某些实例,这些实例是错误的。与rbind(machine, ...)
一样,因为机器不是data.frame 话虽这么说,我认为您与assign
陈述相近。
assign(machine,rbind(get(machine),tempDf))
是否有效?