繁体   English   中英

基于向量重新排列数据框行的顺序

[英]Rearranging order of data frame rows based on a vector

在此处输入图像描述

我上面有以下数据框和一个向量 x= 1, 156, 153, 3, 185。我的向量对应于图片中显示的 node.id 列,我想重新排列数据框的行以匹配我的向量的顺序。 所以数据框行的顺序应该是node.id=1的行,然后是156、153、3、185。 希望我解释得足够好。

我们可以使用match

df1[match(df1$node.id, x),]
#  x     lon   lat node.id          name
#1  1 -122.41 37.70       1 San Francisco
#4 22 -117.16 32.71     156     San Diego
#3 21 -118.24 34.05     153   Los Angeles
#2  3 -115.14 36.16       3     Las Vegas
#5 26 -112.08 38.77     185     Richfield

数据

df1 <-  structure(list(x = c(1, 3, 21, 22, 26), lon = c(-122.41, -115.14, 
-118.24, -117.16, -112.08), lat = c(37.7, 36.16, 34.05, 32.71, 
38.77), node.id = c(1, 3, 153, 156, 185), name = structure(c(5L, 
1L, 2L, 4L, 3L), .Label = c("Las Vegas", "Los Angeles", "Richfield", 
"San Diego", "San Francisco"), class = "factor")), 
class = "data.frame", row.names = c(NA, 
-5L))

x <- c(1, 156, 153, 3, 185)

暂无
暂无

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

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