Reputation: 861
I have a dataframe that looks something like this:
TRUE x_value1 x_value2 y_value1 y_value2 x_id y_id
0 1 4 11 14 1 7
1 2 5 12 15 2 8
0 3 6 13 16 3 9
And I would like to add rows to this data frame and switch x and y, so that in row 4 x_value1=y_value1 and x_id=y_id and y_value1=x_value1...etc.
like this:
TRUE x_value1 x_value2 y_value1 y_value2 x_id y_id
0 1 4 11 14 1 7
1 2 5 12 15 2 8
0 3 6 13 16 3 9
0 11 14 1 4 7 1
1 12 15 2 5 8 2
0 13 16 3 6 9 3
I can do this with for loops, but that takes ages
e.g.
for (i in 1:3)
{ dataframe[i+3,2]<-dataframe[i,4] //for i=1, finds 4th row, column "x_value1" and switches it with first row, column "y_value1"
dataframe[i+3,3]<-dataframe[i,5]
...etc.
}
The example data frame I have (the first table above):
structure(list(TRUE. = c(0L, 1L, 0L), x_value1 = 1:3, x_value2 = 4:6,
y_value1 = 11:13, y_value2 = 14:16, x_id = 1:3, y_id = 7:9), .Names = c("TRUE.",
"x_value1", "x_value2", "y_value1", "y_value2", "x_id", "y_id"
), row.names = c(NA, 3L), class = "data.frame")
Desired (second table above):
structure(list(TRUE. = c(0L, 1L, 0L), x_value1 = 1:3, x_value2 = 4:6,
y_value1 = 11:13, y_value2 = 14:16, x_id = 1:3, y_id = 7:9), .Names = c("TRUE.",
"x_value1", "x_value2", "y_value1", "y_value2", "x_id", "y_id"
), row.names = c(NA, 3L), class = "data.frame")
Upvotes: 2
Views: 5964
Reputation: 420
Instead of rearranging the data frames as others have suggested, you could just rename columns and then let rbind take care of matching up the order:
dat2 <- dat
colnames (dat2) <- colnames (dat) [c (1, 4, 5, 2, 3, 7, 6)]
dat3 <- rbind (dat, dat2)
EDIT: Or more programmatically, to avoid having to type in column indexes, which I keep doing wrong
dat2 <- dat
newnames <- gsub ("(x|y)_", "\\1\\1_", colnames(dat))
newnames <- gsub ("xx_", "y_", newnames)
newnames <- gsub ("yy_", "x_", newnames)
colnames(dat2) <- newnames
dat3 <- rbind (dat, dat2)
Upvotes: 2
Reputation: 263342
To do it more "programatically": use grep with a pattern for the column names:
> grep("y_", names(dat))
[1] 4 5 7
> grep("x_", names(dat))
[1] 2 3 6
dat2 <- dat
# Replace all the dat2 "y_"-names with "x_"-names
colnames(dat2)[grep("y_", colnames(dat))] <-
colnames(dat)[grep("x_", colnames(dat))]
# Replace alldat2 the "x_"-names with "y_"-names
colnames(dat2)[grep("x_", colnames(dat))] <-
colnames(dat)[grep("y_", colnames(dat))]
colnames(dat2)
#[1] "TRUE." "y_value1" "y_value2" "x_value1" "x_value2" "y_id"
#[7] "x_id"
rbind(dat,dat2)
#-----------------
TRUE. x_value1 x_value2 y_value1 y_value2 x_id y_id
1 0 1 4 11 14 1 7
2 1 2 5 12 15 2 8
3 0 3 6 13 16 3 9
4 0 11 14 1 4 7 1
5 1 12 15 2 5 8 2
6 0 13 16 3 6 9 3
Upvotes: 3
Reputation: 6891
If dd is your original dataframe, then you could try:
dd2 <- cbind(dd[1], dd[4:5], dd[2:3],dd[7:6])
names(dd2) <- names(dd)
dd <- rbind(dd, dd2)
Upvotes: 4