If inside of double loop - r

Inside of double loop I create subset of data for each combination of Tv stations with months which is done by loops. For example I have monthsnumbers 7,8,9 and stations A,B,C. It happens that for Month 9 there is no station C.
Then subset is empty and function throws and error of no possible aggregation.
So as you can see I tried to use if statement that if there are 0 rows don't continue with the code but go on to the next loop.
But I still get the same error fck. message
can you please navigate me ?
for (Mesic in monthnumbers){
for (Stanica in TVstations){
Client<-data[data$month ==Mesic & data$Channel_group1 ==Stanica & data$Brand == brand, ]
if (nrow(Client)!=0)
###some code
Client_AGG<-aggregate(formula= Client$BUYING_GRPs ~ Client$Brand,data= Client,FUN = sum)
###some code
}
}
}

Like Gregor commented, there is likely a better way of going about this.
But a quick patch might be to put the error check before the Client<- line because that's where it's looking for a channel that doesn't exist. Check if data$Channel_group1 == Stanica even exists before trying to get data from it.
Another option using for loops is to cycle through what you know is there with something like this:
subsetindex <- unique(data[ ,c('month','Channel_group1')])
for(i in 1:nrow(subsetindex)){
Client<-data[data$month ==subsetindex[i,'month'] & data$Channel_group1 ==subsetindex[i,'Channel_group1'] & data$Brand == brand, ]
#other code
}

Related

R function to check each element and its related children elements to add a result to a list

Suppose we have given dataframe in R. By 0--7, it means it is taking integer values from 0-7 i.e. 0,1,2,3,4,5,6,7.
I am interested in making a function such that
If a[1,1]>alpha, it goes and checks its children i.e. 0--7 consists of a[1,2] and a[2,2].
So,
{a[2,1]>alpha
{a[4,1]>alpha
{a[5,1]>alpha
ps=list.append(0)
else ps=list.append(1)
}}}
Here, alpha is a a threshold. The ps is appended from values of 0 to 15 based on this criteria.
My code is
{for (i in 1:2)
{ if (a[j,i]>alpha)
{if (i%%2==1}
{j=j*2
if (a[j,i]>alpha
###here i want to go recursively i think and where and how should i add append values to the list
if a[j,i+1]>alpha}
if{i%%2==0}
{}
}}
I am stuck and confused at the same time. Any help or advices would be greatly appreciated.
Thanks

How to solve this error of conditional statements and Loops in R?

You can suggest me any sort of answers, not necessarily need using conditional statements and Loops.
I have the data set with several ids and and three alert or groups.
here is the image for the concept:
and here is the actual Data set for one ID: Click me
Concept is:
I have three alert: Relearn - Rebuild - Replace.
and after relearn: rebuild or replace can come but relearn cannot come
and after rebuild: replace can come but relearn cannot come
after replace: relearn and rebuild cannot come. if there is any replace only that can come
I have attached the image and Dataset for better clear understanding and Here is my try:
temp1 = NULL
temp2 = NULL
sql50 = NULL
for(i in 1:nrow(BrokenPins)) #First Loop
{
sql50 = sqldf(paste("select * from rule_data where key = '",BrokenPins[i,1],"'",sep = ""))
for(j in 1:nrow(sql50))
{ #Second Loop
while (head(sql50$Flag,1) == sql50$Flag[j] )
{
temp1 = sql50[j,]
temp2 = rbind(temp2,temp1)
print("Send")
if(j == 1 || sql50$Flag[j] == sql50$Flag[j-1])
{
j = j+1
}
else(sql50$Flag[j] > sql50$Flag[j-1])
{
break
}
}
}
}
First loop will go through each id and second loop will give me all the alert for that id.
so in the image i have added send and dont send. it wont be in actual table. that basically means send means copy it to new dataframe like i am doing above rbind in the code and dont send means dont copy it. This Above piece of code will run but only take the first and end it.
Finally, Based On above Data set Click me: that is for one ID (key), Flag (1 - Relearn, 2-Rebuild,3-replace). so based on this dataset. my output should have Row 1, 2 and 7 because First Relearn[Flag 1] came then Rebuild[Flag 2] then again relearn[Flag 1]cannot come, only rebuild [Flag 2] and replace[Flag 2] can.
can you help me solve this concept?
One thing I notice is that you use else and also provided a condition; you should only use else when you want every case that is not included in the condition of your if statement. Basically, instead of using else(sql50$Flag[j] > sql50$Flag[j-1]) you should be using else if(sql50$Flag[j] > sql50$Flag[j-1]).

If else checking columns in For loop - R

I have a really simple problem that is just stumping me. Im trying to write an if statement in a for loop that checks if a value in a column is greater than another column but for some reason my loop runs once and quits. Here is my code
for (i in nrow(cleaned_us_news)){
school=0
if(Instructional.expenditure.per.student[i] > Out.of.state.tuition[i]){
school = school + 1
}
}
Implementing the suggestions in the comments above.
school=0
for (i in 1:nrow(cleaned_us_news)){
if(Instructional.expenditure.per.student[i] > Out.of.state.tuition[i]){
school = school + 1}
}

Need to Print Value of a Variable using Paste in R

I am trying to create a data frame of various error messages based on Data to be cross checked between two dataframes and storing the message in a vector in an iterative manner . I am using the following snippet for this purpose :
> for(j in 1:nrow(MySQL_Data)){ date_mysql=
> paste("MySQL_Data[",j,",1]") date_red= paste("RED_Data[",j,",1]")
> body= c() if(!date_mysql == date_red) {
> body<- append(body,paste("'There is data missing for date",date_mysql,"in",table2)) }else {
> NULL }}
My table2 variable prints as MYSQL_Data[2,1] instead of the actual value of the variable which is a date
Following is the Output :
"'There is data missing for date MySQL_Data[ 2 ,1] in Dream11_UserRegistration"
Can someone help me with the error that I am committing here..
Thanks in Advance !
Your use of paste in the definitions of data_mysql and data_red makes no sense. I’m assuming that what you actually want is this:
data_mysql = MySQL_Data[j, 1]
data_red = RED_Data[j, i]
Furthermore, you’re resetting body in every loop iteration so it will only ever hold a single element.

Use for loop with if else statement in R

I am trying to create a for loop with an if else statement. My code looks the following:
for(i in 1:length(assignmentlist[,1]))
{if assignmentlist$Approve[i]=="1"
{ApproveAssignment(assignments=assignmentlist$AssignmentId[i],sandbox=T)}
else {RejectAssignment(assignments=assignmentlist$AssignmentId[i],sandbox=T)}}
whereas the "assignmentlist" looks like the following
> assignmentlist
AssignmentId Approve
1 5135 1
2 8963 0
3 6823 0
4 3287 1
Basically I would like to execute the "ApproveAssignment" function for all the entries that have a "1" in the "Approve" collumn. The problem is, that I would like to use the same index (the same i) inside the ApproveAssignment function. Unfortunately, this does not seem to work. Does anyone has a gentle way to avoid this problem?
Edit: The Approve Assignment function is a function that approves a certain assignment of Mechanical Turk over an API and is part of the MTurkR package
Any help yould be appreciated very much!
I don't get the point because the "i" of youy loop can be directly used in your function:
ApproveAssignment <- function(assignments=NULL, sandbox=NULL) cat(i, "was approved\n")
RejectAssignment <- function(assignments=NULL, sandbox=NULL) cat(i, "was rejected\n")
for(i in 1:length(assignmentlist[,1])){
if (assignmentlist$Approve[i]=="1")
ApproveAssignment(assignments=assignmentlist$AssignmentId[i],sandbox=T)
else
RejectAssignment(assignments=assignmentlist$AssignmentId[i],sandbox=T)
}
If, which I assume given I you want to use it inside it, you are the author of ApproveAssignment, you should hand the index over to the function as an additional argument.
ApproveAssignment <- function(assignments, sandbox, index) { ... }
ApproveAssignment and RejectAssignment internally loop through a vector of AssignmentIds to make an assignment-specific call to the API, so all you have to do is feed it a vector of AssignmentIds, no need for the loop or any of the conditionals.
ApproveAssignment(assignments=assignmentlist$AssignmentId[assignmentlist$Approve==1],sandbox=T)
RejectAssignment(assignments=assignmentlist$AssignmentId[!assignmentlist$Approve==1],sandbox=T)

Resources