简体   繁体   English

R:根据不同列的顺序对列重新排序

[英]R: reordering columns based on order of different column

I have the following data: 我有以下数据:

x  y   id
1  2      
2  2    1
3  4    
5  6    2
3  4  
2  1    3

The blanks in column id should have the same values as the next id value. 列ID中的空白应与下一个ID值具有相同的值。 Meaning my data should actually look like this: 这意味着我的数据实际上应如下所示:

x  y   id
1  2    1  
2  2    1
3  4    2
5  6    2
3  4    3
2  1    3

I also have a list: 我也有一个清单:

list[[1]] = 1 3 2

Or alternatively a column: 或作为替代:

c(1,3,2) = 1, 3, 2

Now I would like to reorder my data based on column id accroding to the order in the list. 现在,我想根据列表中列的顺序对列ID重新排序我的数据。 My data should like this then: 我的数据应该是这样的:

x  y   id
1  2   1   
2  2   1 
3  4   3
2  1   3
3  4   2
5  6   2

Is there an efficient way to do this? 有一种有效的方法可以做到这一点吗?

EDIT: I don't think it is a duplicate of in R Sorting by absolute value without changing the data because I do no want to sort by absolute value but by specific order that is given in a list. 编辑:我不认为它是R中按绝对值排序而不更改数据的重复项,因为我不想按绝对值而是按列表中给出的特定顺序进行排序。

A base R option would be (assuming that the blanks in 'id' column is NA ) base R选项为(假设“ id”列中的空白为NA

i1 <- !is.na(df1$id)
df1[i1,][match(df1$id[i1], list[[1]]),] <- df1[i1, ]
df1
#  x y id
#1 1 2 NA
#2 2 2  1
#3 3 4 NA
#4 2 1  3
#5 3 4 NA
#6 5 6  2

If we need to change the NA to succeeding non-NA element 如果我们需要将NA更改为后续的非NA元素

library(zoo)
df1$id <- na.locf(df1$id, fromLast = TRUE)

data 数据

df1 <- structure(list(x = c(1L, 2L, 3L, 5L, 3L, 2L), y = c(2L, 2L, 4L, 
 6L, 4L, 1L), id = c(NA, 1L, NA, 2L, NA, 3L)), class = "data.frame", 
 row.names = c(NA, -6L))

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

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