Im creating a dataframe dynamically and Im using custom names to refer to those data frames.How ever, I can succesfully create the data frames dynamically and add information individually but manually when i try to add a record to it it will run the action but nothing happens. I can open the data frame and it shows as empty
#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
}
All the functions that I've tried are in commented lines from previous answers found on Stack Overflow. I did get working with a for but i dont think that would be really feasible since it will consume a lot of resources plus it doesn't work well when handling various data types . Does anybody have an idea of whats going on, I don't have an error to go by.
I think your code needs quite a lot of cleanup. Make sure you know for yourself at each step what exactly you are handling.
Some hints:
Try to make your code self-contained. If I run your code, I get an error right away, as I don't have wo_raw defined. I understand it's some kind of data.frame, but exactly what is in there? What do I need to do to try to run your code? Also with variables like curYear. I get that it needs to be 2019, but I need to type an awful lot to just get to the problem, I can't just copy-paste.
If you use any libraries, please also include a line for them. I don't know what add_row does or is supposed to do. So I also don't know if that's where your expectations are wrong?
Try to make your code minimal before posting it here. I like the comments and cats sprinkled throughout, but why a line such as 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)? For this problem, just something like subset(wo_raw, wo_raw$mach==machine, net) would suffice
I get that the code works, but try to work out where you are using what kind of objects. if (is.data.frame(netlbs)) {total=sum(netlbs)} may work, but summing a data.frame while you actually just need a column leads to confusion.
When using variables to store the names of other variables such as you are doing, be very aware of what you are actually refering to. For that reason, it's generally advisable to steer clear of these constructs, it's almost always easier to store your results in a list or something similar
Come to that: the variable machine is not a data.frame, it's a character. That character is the name of another variable, which is a data.frame. So (commented out) I see some instances of machine <- NULL and machine$year, those are wrong. As is rbind(machine, ...), as machine is not a data.frame
That being said, I think you got close with the assign-statement.
Does assign(machine,rbind(get(machine),tempDf)) work?
Me and my friend are working on a program that keeps track of swimmers times and all the times totaled is there aggregate. We also ask that the swimmers name which is equal to Name.
We are able to print out...
print('Swimmer had a total time of',aggregates[Name])
but the %Name stop the program from running properly, any suggestions to what we could use instead or maybe what we're doing wrong would be very helpful. Thanks!
print('''%s had a total aggregate time of
''',aggregates[Name] %Name)
Formatting print should be done like print("%s had a t..." % Name, aggregates[Name])
I have my code running in a for loop over dates. The code takes a while to run, and there a couple of days left, but I urgently need whatever results there are. Is there a way of breaking the code/for loop, but keep whatever data has been produced up to now.
Yes. You can press "escape", examine the results and then restart your loop.
for(iii in 1:100000000) force(iii)
# now press ESC
iii
# in my case 1121673
# use this value to restart the loop later:
for(iii in 1121674:100000000) force(iii)
I apologize in advance because I'm extremely new to coding and was thrust into it just a few days ago by my boss for a project.
My data set is called s1. S1 has 123 variables and 4 of them have some form of "QISSUE" in their name. I want to take these four variables and duplicate them all, adding "Rec" to the end of each one (That way I can freely play with the new variables, while still maintaining the actual ones).
Running this line of code keeps giving me an error:
b<- llply(s1[,
str_c(names(s1)
[str_detect(names(s1), fixed("QISSUE"))],
"Rec")],table)
The error is as such:
Error in `[.data.frame`(s1, , str_c(names(s1)[str_detect(names(s1), fixed("QISSUE")) & :
undefined columns selected
Thank you!
Use this to get the subset. Of course there is other ways to do that with simpler code
b<- llply(s1[,
names(s1)[str_detect(names(s1), fixed("QISSUE"))]
],c)
nwnam=str_c(names(s1)[str_detect(names(s1), fixed("QISSUE"))],"Rec")
ndf=data.frame(do.call(cbind,b));colnames(ndf)=nwnam
ndf
# of course you can do
cbind(s1,ndf)
I have a table such as the following:
mafiadb:{"Etzli":{"alive":50,"mafia":60,"vigilante":3,"doctor":4,"citizen":78,"police":40},"Charneus":{"alive":29,"mafia":42,"vigilante":6,"doctor":14,"citizen":53,"police":33}}
There are more nested tables, but I'm just trying to keep it simple for now.
I run the following code to extract certain values (I'm making an ordered list based on those values):
sortmaf={}
for k,v in pairs(mafiadb) do
sortmaf[k]=v["mafia"]
end
That's one of the codes I run. The problem I'm running into is that it doesn't appear you can do arithmetic in a table loop. I tried:
sortpct={}
for k,v in pairs(mafiadb) do
sortpct[k]=(v["alive"]*100)/(v["mafia"]+v["vigilante"]+v["doctor"]+v["citizen"]+v["police"])
end
It returns that I'm attempting to do arithmetic on field "alive." What am I missing here? As usual, I appreciate any consideration in answering this question!
Editing:
Instead of commenting on the comment, I'm going to add additional information here.
The mafiadb database I've posted IS the real database. It's just stripped down to two players instead of the current 150+ players I have listed in it. It's simply structured as such:
mafiadb = {
Playername = {
alive = 0
mafia = 0
vigilante = 0
doctor = 0
police = 0
citizen = 0
}
}
Add a few hundred more playernames, and there you have it.
As for the error message, the exact message is:
attempt to perform arithmetic on field 'alive' (nil value)
So... I'm not sure what the problem is. In my first code, the one with sortmaf, it works perfectly, but suddenly, it can't find v["alive"] as a value when I'm trying to do arithmetic? If I just put v["alive"] by itself, it's suddenly found and isn't nil any longer. I hope this clarifies a bit more.
This looks like a simple typo to me.
Some of your 150 characters is not well written - probably they don't have an "alive" property, or it's written incorrectly, or it's not a number. Try this:
for k,v in pairs(mafiadb) do
if type(v.alive) ~= 'number' then
print(k, "doesn't have a correct alive property")
end
end
This should print the names of the "bad" characters.