简体   繁体   English

交换两列并使用 R 删除数据框中的重复项

[英]exchange two columns and remove the duplicates in a data frame using R

Here is an example to explain what I want to do.这是一个示例来解释我想要做什么。 I have a data frame like:我有一个数据框,如:

X    Y
1    1
1    2
1    3
2    1
2    2
2    3
3    1
3    2
3    3

I want to change it to another format:我想将其更改为另一种格式:

X1    Y1    X2    Y2
1     1     1     1
1     2     2     1
1     3     3     1
......

For two rows in the first table, say X=1, Y=2 and X=2, Y=1.对于第一个表中的两行,假设 X=1, Y=2 和 X=2, Y=1。 They just exchange each other's values.他们只是交换彼此的价值观。 So I want to put such rows in on row, as shown in the second table, and then remove the duplicates.所以我想将这些行放在一行中,如第二个表所示,然后删除重复项。 So, the 'thin and long' table is turned to 'short and fat'.因此,“瘦长”的桌子变成了“短而胖”的桌子。 I know how to do it using two for loops.我知道如何使用两个 for 循环来做到这一点。 But in R, such operation takes for ever.但在 R 中,这样的操作需要永远。 So, can anyone help me with a quick way?那么,任何人都可以快速帮助我吗?

Here is a smallest example:这是一个最小的例子:

The original table is:原表为:

X    Y
1    2
2    1

The transferred table that I want is like:我想要的转移表是这样的:

X1    Y1     X2    Y2
1     2      2     1

So, the rows in the first table that just exchanges values are integrated into one row in the second table and the extra row in the first table is removed.因此,第一个表中仅交换值的行被整合到第二个表中的一行中,而第一个表中的额外行将被删除。

Maybe the code below in base R can work也许下面的基本 R 代码可以工作

dfout <- `names<-`(cbind(r <- subset(df,df$Y>=df$X),rev(r)),
          c("X1","Y1","X2","Y2"))

such that以至于

> dfout
  X1 Y1 X2 Y2
1  1  1  1  1
2  1  2  2  1
3  1  3  3  1
5  2  2  2  2
6  2  3  3  2
9  3  3  3  3

DATA数据

df <- structure(list(X = c(1, 1, 1, 2, 2, 2, 3, 3, 3), Y = c(1, 2, 
3, 1, 2, 3, 1, 2, 3)), class = "data.frame", row.names = c(NA, 
-9L))
library(tidyverse)   
df <- tibble(x1 = 1, 1, 1, 2, 2, 2, 3, 3, 3,
            y1 = 1, 2, 3, 1, 2, 3, 1, 2, 3)
df <- df %>% mutate(x2 = y1, y2 = x1) %>% distinct()

I think this does the trick.我认为这可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM