1

I have a csv file with 5 columns. I want to transpose 4th column of csv file till 10th row. And 5th column of csv file needs to be transformed for every ten rows till the end of the column. I am unable to put a looping for this. Any help is very much appreciated. Thank you!

test<-read.csv("sample.csv",sep=',') 
first<-test$col4[1:10] 
t(first) 
n=length(sample.csv) 
b<-1:1000 
a<-1:10 
for(i in 1:n) { 
  second<-test[a-9:a]
}

I have read 4th colum first 10 rows and transposed them. I wanted to put fifth column in a loop and transpose, later 'rbind' both of these.

Ari B. Friedman
  • 71,271
  • 35
  • 175
  • 235
alex
  • 81
  • 1
  • 4
  • 1
    test<-read.csv("sample.csv",sep=',') first<-test$col4[1:10] t(first) n=length(sample.csv) b<-1:1000 a<-1:10 for(i in 1:n) second<-test[a-9:a] – alex Aug 04 '11 at 04:29
  • 1
    Hi Alex, welcome to SO! Please take a look at this question here to see how to write a good R question, and then update yours accordingly: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Chase Aug 04 '11 at 04:31
  • I have read 4th colum first 10 rows and transposed them. I wanted to put fifth column in a loop and transpose, later 'rbind' both of these. – alex Aug 04 '11 at 04:31
  • 1
    @Chase sorry I am new to stack overflow, I will post in an interpretable way here after – alex Aug 04 '11 at 04:34

1 Answers1

7

To simplify (and to check my understanding), your problem boils down to how to reshape a single column of a data.frame in such a way that this column is split at every 10th element.

There is a function in base R that does this, called unstack. You can use this on your problem as follows.

First set up some dummy data:

df <- data.frame(
    A=1:50,
    B=101:150
)

Now, to use unstack we need to create a temporary data.frame that contains our data to unstack as well as an indicator on how to unstack. The indicator in your case is a repeating vector of 1:10, created using rep:

tmp <- data.frame(
    X=df$B,
    ind=rep(1:10, nrow(df)/10)
)

Then use some unstack magic:

unstack(tmp, X~ind)

   X1  X2  X3  X4  X5  X6  X7  X8  X9 X10
1 101 102 103 104 105 106 107 108 109 110
2 111 112 113 114 115 116 117 118 119 120
3 121 122 123 124 125 126 127 128 129 130
4 131 132 133 134 135 136 137 138 139 140
5 141 142 143 144 145 146 147 148 149 150

Combine it with your the subset of your first column in the original df:

rbind(A=df$A[1:10], unstack(tmp, X~ind))

   X1  X2  X3  X4  X5  X6  X7  X8  X9 X10
A   1   2   3   4   5   6   7   8   9  10
2 101 102 103 104 105 106 107 108 109 110
3 111 112 113 114 115 116 117 118 119 120
4 121 122 123 124 125 126 127 128 129 130
5 131 132 133 134 135 136 137 138 139 140
6 141 142 143 144 145 146 147 148 149 150
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453
Andrie
  • 176,377
  • 47
  • 447
  • 496