【发布时间】:2019-03-22 01:21:18
【问题描述】:
我有一个反应性数据框,其中列名发生变化,Month.Year 名称的列出现故障。我怎样才能把第一个 Month.Year 放在“Current”之后最左边的位置?以下是数据框列的排序方式以及我希望它们的排列方式。
print(colnames(df))
#[1] "ProductCategoryDesc" "RegionDesc" "SourceDesc" "Report"
#[5] "Apr.2019" "Current" "Feb.2019" "Jun.2019"
#[9] "Mar.2019" "May.2019" "Mar.2020"
#the order I want is below
#[1] "ProductCategoryDesc" "RegionDesc" "SourceDesc" "Report"
#[5] "Current" "Feb.2019" "Mar.2019" "Jun.2019"
#[9] "Apr.2019" "May.2019" "Mar.2020"
#####################################################################
#another example of the df
print(colnames(df))
#[1] "ProductCategoryDesc" "RegionDesc" "SourceDesc" "Report"
#[5] "Apr.2019" "Current" "Feb.2019" "Jun.2019"
#[9] "Mar.2019" "May.2019" "Sep.2019"
#the order I want is below
#[1] "ProductCategoryDesc" "RegionDesc" "SourceDesc" "Report"
#[5] "Current" "Feb.2019" "Mar.2019" "Apr.2019"
#[9] "May.2019" "Jun.2019" "Sep.2019"
这里是一些关于 df 外观的信息
print(dput(droplevels(head(d3))))
#below is the output
structure(list(ProductCategoryDesc = structure(c(1L, 1L, 1L,
1L, 1L, 1L), .Label = "CN AMMONIA", class = "factor"), RegionDesc =
structure(c(1L,
1L, 1L, 1L, 1L, 1L), .Label = "AB REG 2 UPPER MIDWEST", class = "factor"),
SourceDesc = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "CN-SD, WATERTOWN
LIQUID", class = "factor"),
Report = structure(1:6, .Label = c("InventoryAvailabletoShip",
"NetCashPosition", "NetMarketPositionTotal", "NonDirectShipPurchase",
"TotalDirectShips", "TotalNonDirectShips"), class = "factor"),
Apr.2019 = c(0, 0, 0, 0, 0, 0), Current = c(0, 0, 0, 0, 0,
0), Feb.2019 = c(0, 0, 240, 240, 0, 240), Jun.2019 = c(0,
0, 0, 0, 0, 0), Mar.2019 = c(0, 0, 0, 0, 0, 0), May.2019 = c(0,
0, 0, 0, 0, 0)), sorted = c("ProductCategoryDesc", "RegionDesc",
"SourceDesc", "Report"), row.names = c(NA, -6L), .internal.selfref =
<pointer: 0x0000000000211ef0>, class = c("data.table",
"data.frame"))
ProductCategoryDesc RegionDesc SourceDesc
Report Apr.2019
1: CN AMMONIA AB REG 2 UPPER MIDWEST CN-SD, WATERTOWN LIQUID
InventoryAvailabletoShip 0
2: CN AMMONIA AB REG 2 UPPER MIDWEST CN-SD, WATERTOWN LIQUID
NetCashPosition 0
3: CN AMMONIA AB REG 2 UPPER MIDWEST CN-SD, WATERTOWN LIQUID
NetMarketPositionTotal 0
4: CN AMMONIA AB REG 2 UPPER MIDWEST CN-SD, WATERTOWN LIQUID
NonDirectShipPurchase 0
5: CN AMMONIA AB REG 2 UPPER MIDWEST CN-SD, WATERTOWN LIQUID
TotalDirectShips 0
6: CN AMMONIA AB REG 2 UPPER MIDWEST CN-SD, WATERTOWN LIQUID
TotalNonDirectShips 0
Current Feb.2019 Jun.2019 Mar.2019 May.2019
1: 0 0 0 0 0
2: 0 0 0 0 0
3: 0 240 0 0 0
4: 0 240 0 0 0
5: 0 0 0 0 0
6: 0 240 0 0 0
【问题讨论】:
-
如果您使用
dput而不是str,那就太好了。这样它就可以复制/粘贴。既然你有一些因素dput(droplevels(head(d3)))应该很好。