vectorization - How can I populate the rows of an R data frame, in which each row represents a day, with a single common value for each day of a year? -
vectorization - How can I populate the rows of an R data frame, in which each row represents a day, with a single common value for each day of a year? -
r: how can populate rows of info frame, in each row represents day, single mutual value each year?
i have info frame consisting of date column, cost column , various other columns derived 2 columns. 1 of columns calculates, each day in given year, percentage alter in cost origin of year (this related before question).
i want add together column holds, each day of given year, percentage alter in cost whole of year. so, if cost rose 10% first lastly day of 2009, column days of 2009 should hold value 10% (or 0.1). if cost fell 2% between first , lastly days of 2010, column each day in 2010 should hold value -0.02 , on.
the code have far is:
require(lubridate) require(plyr) # generate info set.seed(12345) df <- data.frame(date=seq(as.date("2009/1/1"), by="day", length.out=1115),price=runif(1115, min=100, max=200)) # remove weekend days df <- df[!(weekdays(as.date(df$date)) %in% c('saturday','sunday')),] # add together columns later df$year <- as.numeric(format(as.date(df$date), format="%y")) df$month <- as.numeric(format(as.date(df$date), format="%m")) df$day <- as.numeric(format(as.date(df$date), format="%d")) df$daythisyear <- as.numeric(format(as.date(df$date), format="%j")) df <- transform(df, doy = as.date(paste(2000, month, day, sep="/"))) df <- ddply(df, .(year), transform, pctchg = ((price/price[1])-1))
i realise can annual (year-on-year) alter using info frame, this:
df.yr <- ddply(df, .(year), function(x) (x[nrow(x),2]/x[1,2])-1)
...but can't work out how add together figures years column in existing info frame, particularly given (if working 4 years of data) there 4 rows, 1 each year, compared 800 in info frame of daily info used derive 4 rows - mismatch.
it straightforward utilize loop starting @ lastly row of info frame , moving daythisyear column accomplish (if daythisyear on current row larger daythisyear on row below, have alter in year, take new value row utilize in column beingness added etc). nevertheless, sense sure there must more r-colloquial approach using apply function or ddply, have far studiously avoided tackling. question is:
q. how calculate annual alter in value of column , insert value, new column, every row year?
i've not yet converted beingness ddply user, preferring instead utilize ave
when obvious solution. suspect code translate across:
df$pctyrchng <- ave(df$price, df$year, fun=function(x) tail(x,1)/head(x,1) - 1) unique(df$pctyrchng) #[1] -0.03259032 -0.05781901 0.35932519 0.04246669
r vectorization plyr
Comments
Post a Comment