1
votes

so this is a very silly question and I am pretty sure I am missing something extremely obvious.

I have 12 months in a vector from Jan to Dec and I have a dataframe that has yearmonth values so 201601, 201602, 201604 for Jan,Feb,March.

The data frame will always be sorted and starts from Jan (201601)

I am extracting the length of this dataframe and I want to map each element of the dataframe against my 12 month vector.

When I run lapplay I get a partial solution, if the dataframe is of length 15 I get Jan - Dec mapped and 3 NAs, I want the mapping to continue so it would be Jan - Mar instead.

This is what I have so far

monthName <- c("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec")
entry <- data.frame("test"=c("1","2","3","4","5","6","7","8","9","10","11","12","13","14","15"))

month <- unlist(lapply(1:length(entry$test), function (x) monthName[x]))

> month

[1] "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec" NA NA NA

As pointed out HubertL this is a simple and elegant solution rep_len(monthName, length(entry$test))

1
rep_len(monthName, length(entry$test))HubertL
ok wow that was so bloody simple and i looked through rep_len as well! Thank you, I shall go apply palm to face for a few minutes now hahauser3674993
We can blame the default stringsAsFactors =TRUE for that :)Silence Dogood
ya I see that nowSilence Dogood
entry$test <- as.numeric(as.character(entry$test)); monthName[ifelse(entry$test > 12, entry$test %% 12, entry$test)] would seem to make more sense to me.thelatemail

1 Answers

0
votes

As pointed out by HubertL the fix to this current problem is:

rep_len(monthName, length(entry$test))

Thank you HubertL