2
Staff I am developing a program in R language, the same compares data from two data.frame
and writes in a third, the program presents several conditional structures of the type else if
within two repeating structures of the type for
and if any of these is satisfied the data is recorded in this third data.frame
. The part of the code that saves the data in the third data.frame
if repeated several times during the code I would like to know if there is any way to create a type of function that I can pass the parameters so that it makes the recording without having to repeat it every time? In the simplified example below I put only 3 conditions, but in the real program are 13, for this example the part that repeats is always:
tabela3$coluna1[k]<-tabela2$coluna1[j]
tabela3$coluna2[k]<-tabela2$coluna2[j]
tabela3$coluna3[k]<-tabela2$coluna3[j]
tabela3$coluna4[k]<-tabela2$coluna4[j]
tabela3$coluna5[k]<-tabela2$coluna5[j]
Obs: I tried to create a function, but it didn’t work!
k<-1
for(i in 1:nrow(tabela1)){
for(j in 1:nrow(tabela2)){
if (condicao 1 for satisfeia){
tabela3$coluna1[k]<-tabela2$coluna1[j]
tabela3$coluna2[k]<-tabela2$coluna2[j]
tabela3$coluna3[k]<-tabela2$coluna3[j]
tabela3$coluna4[k]<-tabela2$coluna4[j]
tabela3$coluna5[k]<-tabela2$coluna5[j]
k<- k+1
}
else if(condicao 2 for satisfeita){
tabela3$coluna1[k]<-tabela2$coluna1[j]
tabela3$coluna2[k]<-tabela2$coluna2[j]
tabela3$coluna3[k]<-tabela2$coluna3[j]
tabela3$coluna4[k]<-tabela2$coluna4[j]
tabela3$coluna5[k]<-tabela2$coluna5[j]
k<-k+1
}
else if(condicao 3 for satisfeita){
tabela3$coluna1[k]<-tabela2$coluna1[j]
tabela3$coluna2[k]<-tabela2$coluna2[j]
tabela3$coluna3[k]<-tabela2$coluna3[j]
tabela3$coluna4[k]<-tabela2$coluna4[j]
tabela3$coluna5[k]<-tabela2$coluna5[j]
k<-k+1
}
}
Thank you.
I tested both suggestions, but the only one that worked was this "<<-", but as it was said can cause side effects! I get a little frustrated with R by the difficulty of solving a problem that is simple to solve in other languages. Thank you.
– aguch
What was the error message for the second option? If you put part of your data would be easier to help:
dput(head(tabela2))
anddput(head(tabela3))
.– Willian Vieira
This is the code I just modified the name of the tables and columns, but the structure is the same. Thank you
– aguch