由于没有提供数据,我创建了虚拟数据框来模拟您尝试重新排列的数据。
第一个数据框 ,df1包含字符列five, two, three, one, 并按four以下顺序:
df1 <- data.frame(
five = character(),
two = character(),
three = character(),
one = character(),
four = character()
)
第二个数据框df2包含一个标题names为列名的列df1,按其等效数字排序。
df2 <- data.frame(names = c('one', 'two', 'three', 'four', 'five'))
可以使用包含列索引或列名称的有序向量对数据框进行排序。在这种情况下,我们可以调用df1[, as.character(df2$names)]sortdf1的列。as.character()用于将df1列名的因子向量转换为字符串向量。
If you are keen on using data.table::setcolorder(), you can call setcolorder(df1, as.character(df2$names)) instead. A benefit of this method is that you do not have to assign the resulting data frame to the variable df1. Your attempt did not work because (1) there is no key parameter for the setcolorder() function (there is only neworder) and (2) your df2$names was likely a factor vector (you can check by calling class(df2$names)).