R write.table with rbind

Asked

Viewed 115 times

0

Hello,

I have the following variables: year, area and a series of data. At each loop of area and year, I make an average of my data.

for(area in 1:10){ 
   for(ano in 1:20){
      calculo_coeficiente<- mean(d) }}

** d depending on area and year

The point is that I want to do a single write.table, with all variables and all loops, where I could get . txt:

area1 ano1 calculo_coeficiente1
area1 ano2 calculo_coeficiente2
area1 ano3 calculo_coeficiente3
....
area2 ano1 calculo_coeficiente1
area2 ano2 calculo coeficiente2
....
area3 ano1 calculo_coeficiente1
area3 ano2 calculo_coeficiente2

I tried using:

output<-rbind(data.frame(c(area),data.frame(ano),data.frame(coeficiente)),output)

write.table(output,"tabela.txt",sep=""),row.names =F,col.names=F)

and

output<- rbind(cbind(area[area],ano[area], media[area]))
output<- rbind(cbind(area[ano],ano[ano], media[ano]))

But it didn’t work. Would anyone know to give me a light? Thank you!

  • The structure of the data is not understood. Can you please, edit the question with the departure of dput(area) or, if the vector is too large, dput(head(area, 20))? And the same for ano and calculo_coeficiente. Always with dput().

  • It seems not necessary rbind. output <- data.frame(area, ano, calculo_coeficiente) looks like it’s coming.

  • Thank you very much! I’m sorry, my code is much more complex and involves many other things 'out of this context', but I will try to explain. I have an area (length=1549) and a year of (length=29) and a series of data (d=28). At each loop, area=1, year=1, I make an average of d. And so, successively, area=1, year=2.... What I need, is to save a txt, with all the area, year and average of my data. Got confused? Anything warns me.

  • There is a syntax error on this line write.table(output,"tabela.txt",sep=""),row.names =F,col.names=F): you are closing the parentheses twice, but only opens one.

  • Thanks @Tomásbarcellos. But unfortunately this is just a detail to save, the biggest problem is in the structuring of the loop and write.table'.

1 answer

1


I can’t comment, so I’ll put it in answer. You can give some data frames as an example to understand the problem.

Does it help?

output<- rbind(cbind(area, ano, coeficiente),output)

Edit!

> area = c(1:10)
> ano= c(2001:2010)
> 
> teste <- data.frame()
> for(area in 1:10){ 
+    for(ano in 2001:2010){
+       teste <<- rbind(cbind(area,ano, mean(area+ano)),teste) }}
> 
> 
> head(teste)
  area  ano   V3
1   10 2010 2020
2   10 2009 2019
3   10 2008 2018
4   10 2007 2017
5   10 2006 2016
6   10 2005 2015
  • Thank you so much @João!

  • I edited the answer with rbind, in principle it should help! Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.