Home > OS >  R : df.list[[i]] deletes every first row from multiple dataframes when tried to combine by row
R : df.list[[i]] deletes every first row from multiple dataframes when tried to combine by row

Time:12-03

Lets say I've this <20 table in one .csv file, in multiple columns. I able to separate each tables using:

d <- split(table.df, r) 

and I able to transpose it to rows of two columns using code below:

for (i in 1:length(d)) { 
  
  df <- data.frame(d[i])
  
  new.df <- stack(df)

  df.list[[i]] <- new.df
}  

The example of stack data (new.df) is structured as below:

values  ind
*    X2000.Day
15   X2000.Jan
17.5 X2000.Jan
0.5  X2000.Jan
*    X2001.Day
33.7 X2001.Jan
0    X2001.Jan
1.8  X2001.Jan
*    X2002.Day
0    X2002.Jan
0    X2002.Jan
0    X2002.Jan

I also remove row that contain "*" by using

new.df <- new.df[!(new,df$values=="*"),] 

However, when I try to combine all new.df by row using code below, which I'm referring to here

merge.row = do.call(rbind, df.list)

the df.list[[i]] deletes every first row when the new year begins, , which looks like this:

values  ind
17.5 X2000.Jan
0.5  X2000.Jan
0    X2001.Jan
1.8  X2001.Jan
0    X2002.Jan
0    X2002.Jan

I'm not sure what I did wrong, and I'm hoping you guys can point out what's wrong with my code. Thanks!

CodePudding user response:

I think the issue is in your loop when you save new.df as a list element in df.list[[i]]. Usually when you save elements to a list in a loop you need to initiate a blank list item. Try changing your code like this:

df.list<-list()

for (i in 1:length(d)) { 
  
  df <- data.frame(d[i])
  
  new.df <- stack(df)

  df.list[[i]] <- new.df
} 
  • Related