Reputation: 13
I have a data frame (m2) with 1127 columns and 314 rows. Starting at column 1, I need to replace the values in every 5th column with the 1st value in the adjoining column. I have been able to do this for individual columns selecting by column name as here:
m2$Col1<-m2[1,2]
m2$Col6<-m2[1,7]
m2$Col11<-m2[1,12]
or by a very clunky reassign/recombine:
newcol1<-replace(m2[,1],1:314,m2[1,2])
m2<-cbind(newcol1,m2[,2:1127])
newcol2<-replace(m2[,6],1:314,m2[1,7])
m2<-cbind(m2[,1:5],newcol2,m2[,7:1127])
newcol3<-replace(m2[,11],1:314,m2[1,12])
m2<-cbind(m2[,1:10],newcol3,m2[,12:1127])
I am hoping to find a way to automate this for the data frame. I am not yet literate in for loops. Can something like this be done with a function?
Upvotes: 1
Views: 1501
Reputation: 263301
Initial thought;
m2[, c(TRUE, rep(FALSE,4) )] <- m2[ , c(FALSE, TRUE, FALSE,FALSE,FALSE) ]
That was thinking this was a column-for-column replacement, but re-reading the question, it appears not;
Perhaps:
m2[, c(TRUE, rep(FALSE,4) )] <- rep( m2[1 , c(FALSE, TRUE, FALSE,FALSE,FALSE) ], each=nrow(m2) )
But that was it either and it needed an unlist operation to provide a tested solution:
m2 <- as.data.frame(matrix(1:150, nrow=10))
m2[, c(TRUE, rep(FALSE,4) )] <-
unlist(rep( m2[ 1, c(FALSE, TRUE, FALSE,FALSE,FALSE) ], each=nrow(m2) ))
> m2
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14 V15
1 11 11 21 31 41 61 61 71 81 91 111 111 121 131 141
2 11 12 22 32 42 61 62 72 82 92 111 112 122 132 142
3 11 13 23 33 43 61 63 73 83 93 111 113 123 133 143
4 11 14 24 34 44 61 64 74 84 94 111 114 124 134 144
5 11 15 25 35 45 61 65 75 85 95 111 115 125 135 145
6 11 16 26 36 46 61 66 76 86 96 111 116 126 136 146
7 11 17 27 37 47 61 67 77 87 97 111 117 127 137 147
8 11 18 28 38 48 61 68 78 88 98 111 118 128 138 148
9 11 19 29 39 49 61 69 79 89 99 111 119 129 139 149
10 11 20 30 40 50 61 70 80 90 100 111 120 130 140 150
Upvotes: 0
Reputation: 6522
It's difficult without the actual data to check but I think you mean:
#all the fifth cols
fifth= seq(1, ncol(m), 5)
# and the adjacent
adj= fifth+1
m[,fifth]= m[1,adj]
NB this doesn't check for correctness of your columns i.e. that there is an adjacent column. I just assume from your description there is.
Upvotes: 2