On Wed, Jan 18, 2012 at 02:48:48AM -0800, Nerak wrote: > Dear all, > I have a question concerning manipulating data of several columns of a > dataframe at the same time. > I manage to do it for one column (with the use of the specific name for this > column). > In each columns, I have 60 values. But I should reorganize the values > (because I created this as an output before and I want to compare it with an > other dataset). I want that the value on row 2 becomes the value of row 1, > value 3 value 2 and so on. The first value would be NA. > > If I would do this for 1 column (with the name depth_1), I would do it like > this: > > for (t in 2:60) > { > results$depth[t]<-new$depth_1[t-1] > } > > > # But in my dataset I have 91 columns and I would like to find a way not > having to write this for every column… > # I cannot give my dataset where I’m working on so I created one just for > trying it out and to provide a reproducible example. I created a data frame > ‘new’ with 26 columns and 60 rows. I named the columns all in a similar way > using ‘C <- seq(1,13.5,0.5)’. That means that all my column names are > structured in the same way: depth_1 ; depth_1.5, depth_2; depth_2.5 and so > on. > > C <- seq(1,13.5,0.5) > > a<-c(1:60) > b<-c(2:61) > c<-c(3:62) > d<-c(1:60) > e<-c(2:61) > f<-c(3:62) > g<-c(1:60) > h<-c(2:61) > i<-c(3:62) > j<-c(1:60) > k<-c(2:61) > l<-c(3:62) > m<-c(1:60) > n<-c(2:61) > o<-c(3:62) > p<-c(1:60) > q<-c(2:61) > r<-c(3:62) > s<-c(1:60) > t<-c(2:61) > u<-c(3:62) > v<-c(1:60) > w<-c(2:61) > x<-c(3:62) > y<-c(1:60) > z<-c(2:61) > > new<-data.frame(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z) > names(new)<-c(paste('depth_',C,sep='')) >
If you want to keep the vector of row names unchanged, try the following. shift <- function(x) { c(NA, x[1:(length(x)-1)]) } new1 <- as.data.frame(lapply(new, shift)) new[c(1:5, 57:60), 1:5] depth_1 depth_1.5 depth_2 depth_2.5 depth_3 1 1 2 3 1 2 2 2 3 4 2 3 3 3 4 5 3 4 4 4 5 6 4 5 5 5 6 7 5 6 57 57 58 59 57 58 58 58 59 60 58 59 59 59 60 61 59 60 60 60 61 62 60 61 new1[c(1:5, 57:60), 1:5] depth_1 depth_1.5 depth_2 depth_2.5 depth_3 1 NA NA NA NA NA 2 1 2 3 1 2 3 2 3 4 2 3 4 3 4 5 3 4 5 4 5 6 4 5 57 56 57 58 56 57 58 57 58 59 57 58 59 58 59 60 58 59 60 59 60 61 59 60 Petr Savicky. ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.