Reputation: 764
SUppose I have a data frame
data=data.frame(X1_C1=c(1:5),
X2_C1=c(11:15),
X3_C1=c(111:115),
X1_C2=c(2:6),
X2_C2=c(21:25),
X3_C2=c(211:215),
X1_C3=c(3:7),
X2_C3=c(31:35),
X3_C3=c(311:315))
> data
X1_C1 X2_C1 X3_C1 X1_C2 X2_C2 X3_C2 X1_C3 X2_C3 X3_C3
1 1 11 111 2 21 211 3 31 311
2 2 12 112 3 22 212 4 32 312
3 3 13 113 4 23 213 5 33 313
4 4 14 114 5 24 214 6 34 314
5 5 15 115 6 25 215 7 35 315
I would like to swap the value so columns in variable ending with _C2
and _C3
. For example, swap X1_C2
and X1_C3
, X2_C2
and X2_C3
and similar for other Xs
in C2
and C3
Any help in appreciated
Upvotes: 0
Views: 44
Reputation: 26218
a dplyr
approach, not as good as TIC has suggested, but if it may help
data %>%
rename_with(~str_replace(., '_C2', '_CC3'), ends_with('_C2')) %>%
rename_with(~str_replace(., '_C3', '_C2'), ends_with('_C3')) %>%
rename_with(~str_replace(., '_CC3', '_C3'), ends_with('_CC3'))
X1_C1 X2_C1 X3_C1 X1_C3 X2_C3 X3_C3 X1_C2 X2_C2 X3_C2
1 1 11 111 2 21 211 3 31 311
2 2 12 112 3 22 212 4 32 312
3 3 13 113 4 23 213 5 33 313
4 4 14 114 5 24 214 6 34 314
5 5 15 115 6 25 215 7 35 315
Upvotes: 2
Reputation: 101034
If you want to swap columns (not just the names), you can try the code below
> data[c(matrix(names(data), 3)[, c(1, 3, 2)])]
X1_C1 X2_C1 X3_C1 X1_C3 X2_C3 X3_C3 X1_C2 X2_C2 X3_C2
1 1 11 111 3 31 311 2 21 211
2 2 12 112 4 32 312 3 22 212
3 3 13 113 5 33 313 4 23 213
4 4 14 114 6 34 314 5 24 214
5 5 15 115 7 35 315 6 25 215
If you want to swap the names
> setNames(data, c(matrix(names(data), 3)[, c(1, 3, 2)]))
X1_C1 X2_C1 X3_C1 X1_C3 X2_C3 X3_C3 X1_C2 X2_C2 X3_C2
1 1 11 111 2 21 211 3 31 311
2 2 12 112 3 22 212 4 32 312
3 3 13 113 4 23 213 5 33 313
4 4 14 114 5 24 214 6 34 314
5 5 15 115 6 25 215 7 35 315
Upvotes: 2
Reputation: 10375
How about changing the columns names?
tmp1=grepl("_C2",colnames(data))
tmp2=grepl("_C3",colnames(data))
colnames(data)[tmp1]=gsub("_C2","_C3",colnames(data)[tmp1])
colnames(data)[tmp2]=gsub("_C3","_C2",colnames(data)[tmp2])
Upvotes: 0