【问题标题】:How to reorder column names in R numerically?如何以数字方式对 R 中的列名重新排序?
【发布时间】:2019-07-15 10:29:55
【问题描述】:

我正在将一些长格式数据转换为宽格式。当我将行转换为列时,它们以 1、10、100 而不是 1、2、3 等顺序出现。我该如何解决这个问题?我有 100 行,所以我不想手动输入订单。

我知道这是列名是字符串的问题,我尝试简单地使用 select(),但是,这会删除我的集群列。我也尝试过重命名列(data <- data[c("A", "B", "C")]) 的标准方法。

我还查看了以下线程,但似乎无法解析出来。 Reordering columns in a large dataframe Preserve order of columns when going from wide to long format R: Reorder columns from dcast output numerically instead of lexicographically

这是我的代码:

library(reshape2)
library(data.table)
library(tidyverse)
library(tidyr)
library(gtools)
library(stringr)

rf_83_88 <- read.csv('Google Drive File Stream/My Drive/Bang_RIA/bang_83_05_rainfall_avg/Bangladesh-precipitation-decadal-83-88.csv')


groupdata_1 <- dcast(setDT(rf_83_88), cluster ~
                     paste0("precipitation", rowid(cluster)), value.var = "precipitation")

这是它产生的 df 样本:

cluster        precipitation1  precipitation10 precipitation100
Akhai Bari _ 1   0               11.730278        11.12267
Akhai Bari _ 2   0               10.130148        12.53500

当我尝试时:

test_select <- select(groupdata_1, num_range("precipitation", 0:nrow(groupdata_1))

,df 变得有序,但是它丢弃了簇。

我对 R(和堆栈)比较陌生,并尝试阅读文档无济于事。任何帮助,将不胜感激。谢谢!

【问题讨论】:

  • DF[,-1] &lt;- DF[,-1][, order(as.numeric(gsub("precipitation", "", names(DF[, -1]))))]?
  • 我在尝试您的解决方案时收到此错误```[&lt;-.data.table(*tmp*, , -1, value = c(1L, 112L, 144L, 155L, 中的错误): 项目 1 j 中的列号为 -1,超出范围 [1,ncol=221]。在 j 中使用列名来添加新列。```我尝试将 -1 替换为 "cluster" 并收到此消息:@ 987654333@但列顺序没有变化
  • 嗯,你没有说你有一个data.table。我假设你有一个常规的 data.frame。也许setcolorder(DT, c(1, order(as.numeric(gsub("precipitation", "", names(DT)[-1]))) + 1)).

标签: r dataframe data-science


【解决方案1】:

OP 已在 cmets 中澄清他们实际上有一个 data.table 而不是常规的 data.frame。

  1. 提取列名,去掉第一个列名:

    names(DT)[-1]

  2. 从列名中提取数字(或者更简单,删除“沉淀”一词):

    gsub("precipitation", "", names(DT)[-1])

  3. 现在找到这些数字的排序顺序(将它们变成数值后):

    order(as.numeric(gsub("precipitation", "", names(DT)[-1])))

  4. 现在我们只需要将第一列添加到此订单中:

    c(1, order(as.numeric(gsub("precipitation", "", names(DT)[-1]))) + 1)

  5. 并将订单传递给setcolorder:

    setcolorder(DT, c(1, order(as.numeric(gsub("precipitation", "", names(DT)[-1]))) + 1))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    相关资源
    最近更新 更多