我想在r中对月份数据进行排序,我尝试使用此
Data_Full$Year_Month <- paste(Data_Full$Year, Data_Full$Month, sep = "")
for(i in 1: length(Data_Full$Year_Month)){
if(length(Data_Full$Year_Monthi[i] == 5)){
Data_Full$Year_Month[i] <- paste(substr(Data_Full$Year_Month[i], 1, 4), "0", substr(Data_Full$Year_Month[i], 5, nchar(Data_Full$Year_Month[i])), sep = "")
} else
{
Data_Full$Year_Month[i] <- Data_Full$Year_Month[i]
}
i
}
一旦我得到这个,我会对它进行排序,但我无法做到这一点
答案 0 :(得分:0)
此代码将为您提供一个新的日期列,然后您可以正常排序。
# Test dataframe
Data_Full <- data.frame(Year = rep(2017,12),
Month = c(12:1))
# Create a date column from Month and Year
Data_Full$Date <- as.Date(apply(Data_Full, 1, function(x){
paste0(x["Year"], ifelse(nchar(as.character(x["Month"])) == 2, x["Month"], paste0(0,x["Month"])), "01")
}), format = "%Y%m%d")
# Order dataframe by date
Data_Full <- Data_Full[with(Data_Full, order(Date)),]