Writing R functions to support vectors -
i have function:
pcal.getperiodfordate <- function(date_) { dateobject <- as.posixlt(date_) calendarstart <- pcal.getcalendarstart(dateobject$year + 1900) difference <- dateobject - calendarstart if(difference < 0) { calendarstart <- pcal.getcalendarstart(dateobject$year + 1899) difference <- dateobject - calendarstart } period <- difference / 28 week <- ifelse(period < 1, ceiling(period * 4), ceiling((period - floor(period)) * 4)) return(list(period = as.numeric(ceiling(period)), week = week)) } i have data frame following structure
> str(sells) 'data.frame': 73738 obs. of 4 variables: $ loc_nbr: chr "2" "2" "2" "2" ... $ sls_dt : date, format: "2015-02-01" "2015-02-02" "2015-02-03" "2015-02-04" ... $ sales : num 1 2 3 4 5 ... i want able this:
sells$pd <- pcal.getperiodfordate(sells$sls_dt)$period however, ton of warnings:
warning messages: 1: in if (year < 2000) { : condition has length > 1 , first element used 2: in seedyear:year : numerical expression has 73738 elements: first used 3: in if (difference < 0) { : condition has length > 1 , first element used 4: in if (year < 2000) { : condition has length > 1 , first element used 5: in seedyear:year : numerical expression has 73738 elements: first used the function works fine passing 1 value:
> pcal.getperiodfordate('2015-09-29') $period [1] 9 $week [1] 3 how can make work?
the function if not vectorized in r means can use vectors of length 1. using if bigger vectors cause warnings serious warning should not ignored if uses first element of vector cause trouble. see simple case:
> if(c(1,-5,3) > 0) print('hello') [1] "hello" warning message: in if (c(1, -5, 3) > 0) print("hello") : condition has length > 1 , first element used in case although there -5 in vector above hello returned because if checks first element of vector.
in order use if vector have 3 options:
all
use function all when want every element of vector confirm condition:
if( all(c(1,-5,3) > 0) ) print('hello') #this not return any
use function any when want @ least 1 of elements confirm condition:
> if( any(c(1,-5,3) > 0) ) print('hello') [1] "hello" apply family
use *apply family when need vector same size 1 in check (c(1,-5,3) here) each element checked against condition:
> vapply(c(1,-5,3), function(x) { if (x > 0) 'hello' else na_character_ }, character(1)) [1] "hello" na "hello" i cannot run function tell version of above need not know how difference used or pcal.getcalendarstart should enough fix warnings get. use 1 of above according how want if behave , should no warnings.
Comments
Post a Comment