![](/img/trans.png)
[英]How to write an R function that creates a series of plotly plots interspersed with markdown
[英]How to write my first function in R markdown?
我正在用R Markdown編寫我的第一個函數,但似乎無法正常工作。 有人可以幫忙嗎?
我正在使用一個字符變量,該變量以yyyy-mm-dd格式列出日期,我希望將其轉換為格式為“ Jan”,“ Feb”等的日期。為此,我使用了2個步驟:
All.abs$MonthBeginning= as.Date(All.abs$MonthBeginning, format= "%Y-%m-%d")
All.abs$MonthBeginning= as.Date(All.abs$MonthBeginning, format= "%b")
我想對其他2個data.frames(稱為“ Carbs”和“ Pip.Taz”)中的相同變量(MonthBeginning)遵循相同的過程,而不必編寫6行代碼。
我編寫了如下函數(名為chart_months),但似乎無法正常工作:
chart_months= function(x) {
x= as.Date(x, format= "%Y-%m-%d")
x= as.Date(x, format= "%b")
}
chart_months(All.abs$MonthBeginning)
chart_months(Carbs$MonthBeginning)
chart_months(Pip.Taz$MonthBeginning)
有人可以幫忙嗎?
這不會這樣做:
然后使用以下代碼將日期更改為“ Jan”等:
All.abs$MonthBeginning= as.Date(All.abs$MonthBeginning, format= "%b")
您要使用format
:
> string_date = "2001-05-22"
> date_object = as.Date(string_date, format="%Y-%m-%d")
> short_month = format(date_object, "%b")
> short_month
[1] "May"
因此,您的功能應為:
get_short_month = function(string_date){
date_object = as.Date(string_date, format="%Y-%m-%d")
short_month = format(date_object, "%b")
return(short_month)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.