【发布时间】: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] <- DF[,-1][, order(as.numeric(gsub("precipitation", "", names(DF[, -1]))))]? -
我在尝试您的解决方案时收到此错误```
[<-.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