开发者

transposing a column (about 10,000 rows) for every 10 rows

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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜