我有一个看起来像这样的数据框:
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
我想向这个数据框添加行并切换 x 和 y,以便在第 4 行 x_value1=y_value1 和 x_id=y_id 和 y_value1=x_value1...等。
像这样:
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
我可以用 for 循环做到这一点,但这需要很长时间
例如
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.
}
我拥有的示例数据框(上面的第一个表):
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")
期望(上面的第二个表):
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")