gpt4 book ai didi

r - 在数据框中复制粘贴列值

转载 作者:行者123 更新时间:2023-12-02 06:36:37 24 4
gpt4 key购买 nike

我有一个看起来像这样的数据框:

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")

最佳答案

如果 dd 是您的原始数据框,那么您可以尝试:

dd2 <- cbind(dd[1], dd[4:5], dd[2:3],dd[7:6])

names(dd2) <- names(dd)

dd <- rbind(dd, dd2)

关于r - 在数据框中复制粘贴列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17028952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com