Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9245179
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 18, 20262026-06-18T09:12:27+00:00 2026-06-18T09:12:27+00:00

I am trying to mean center (aka demean, scale) a variable by 3 dimensions:

  • 0

I am trying to mean center (aka demean, scale) a variable by 3 dimensions: year, month, and region using the sqldf package in R.

Here is exactly what I want to do using the plyr package:

## create example data
set.seed(145)
v = Sys.Date()-seq(1,425)
regions = LETTERS[1:6]
VAR1_DATA = as.data.frame(expand.grid(v,regions))
VAR1_DATA$VAR1 = rpois(nrow(VAR1_DATA), 4) + runif(nrow(VAR1_DATA), 25,35)
names(VAR1_DATA) = c("DATE","REG","VAR1")


## mean center VAR1 by year, month and region using plyr:
lapply(c('chron','plyr'), require, character.only=T)
table1 = cbind(MONTH = months(as.POSIXlt(VAR1_DATA[,'DATE'])),
            YEAR = years(as.POSIXlt(VAR1_DATA[,'DATE'])),
            VAR1_DATA)
table2 = ddply(table1, c('YEAR','MONTH','REG'), transform, MEAN.V1 = mean(VAR1), DEMEANED.V1 = VAR1 - mean(VAR1))
head(table2)

##      MONTH YEAR       DATE REG     VAR1  MEAN.V1 DEMEANED.V1
## 1 December 2011 2011-12-31   A 30.03605 34.69316  -4.6571064
## 2 December 2011 2011-12-30   A 31.69130 34.69316  -3.0018600
## 3 December 2011 2011-12-29   A 35.46342 34.69316   0.7702634
## 4 December 2011 2011-12-28   A 32.09727 34.69316  -2.5958876
## 5 December 2011 2011-12-27   A 36.51519 34.69316   1.8220386
## 6 December 2011 2011-12-26   A 35.65338 34.69316   0.9602236

Now I would like to replicate the result above using SQLite / SQL. Below is the SQLite code I’m currently using to attempt to accomplish this (Warning: the code below does not work!). I have included it here to illustrate my SQLish thought process:

require(sqldf)

sqldf("
       SELECT
       strftime('%m', t1.DATE) AS 'MONTH', 
       strftime('%Y', t1.DATE) AS 'YEAR',
       t1.DATE,
       t1.REG,
       t1.VAR1,
       t2.MVAR1 AS 'MO_AVG_VAR1',
       (t1.VAR1-t2.MVAR1) AS 'DEMEANED_VAR1',
       FROM VAR1_DATA AS t1,
       (
           SELECT
           DATE,
           REG,
           avg(VAR1) AS MVAR1,
           FROM VAR1_DATA
           GROUP BY strftime('%Y', DATE), strftime('%m', DATE), REG
       ) AS t2
      WHERE t1.REGION = t2.REGION
      AND t1.DATE = t2.DATE
      GROUP BY strftime('%Y', t1.DATE), strftime('%m', t1.DATE), t1.REGION
      ORDER BY YEAR, MONTH, REG
      ;")

Question: is this calculation possible in SQLite / sqldf — if so, how? Bonus points if the answer also provides the (slightly modified?) “regular SQL” (i.e. mySQL, PostgreSQL, etc.) implementation.

Many thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-18T09:12:29+00:00Added an answer on June 18, 2026 at 9:12 am

    Try this:

    ## set order so we can compare it later
    
    table2 <- table2[order(table2$DATE, table2$REG), ]
    
    ## use a single SQL statement
    
    s1 <- "select 
              rowid, 
              *, 
              strftime('%Y-%m', DATE * 3600 * 24, 'unixepoch') AS 'YM' 
           from VAR1_DATA"
    s2a <- "select a.*, 
             avg(b.VAR1) 'MEAN.V1', 
             a.VAR1 - avg(b.VAR1) 'DEMEANED.V1'
           from ($s1) a, ($s1) b using (YM, REG)
           group by a.rowid
           order by a.DATE, a.REG"
    # substitute s1 into s2a giving the single sql statement:
    #    cat(fn$identity(s2a), "\n")
    tab2 <- fn$sqldf(s2a)
    
    # ensure they compare to the plyr solution
    all.equal(table2$MEAN.V1, tab2$MEAN.V1) # TRUE
    all.equal(table2$DEMEANED.V1, tab2$DEMEANED.V1) # TRUE
    

    Same but use two SQL statements:

    # s1 is as above
    tab1 <- sqldf(s1)
    s2b <- "select a.*, 
             avg(b.VAR1) 'MEAN.V1', 
             a.VAR1 - avg(b.VAR1) 'DEMEANED.V1'
           from tab1 a, tab1 b using (YM, REG)
           group by a.rowid
           order by a.DATE, a.REG"
    tab2 <- sqldf(s2b)
    
    # ensure they compare to the plyr solution
    all.equal(table2$MEAN.V1, tab2$MEAN.V1) # TRUE
    all.equal(table2$DEMEANED.V1, tab2$DEMEANED.V1) # TRUE
    

    NOTE: Have completely revised above based on comments.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

am trying to calculate mean and variance using 3X3 window over image(hXw) in opencv...here
I am trying to calculate a rolling mean using plyr. The data is at
I am trying to create a form using only JavaScript. I mean create a
Im trying to compute a 24 hour rms (root mean squared) from a dataset
I am trying to rotate a vector of elements in C++. What I mean
I am trying to make a counter. What I mean by that is a
EDIT: What I mean is displaying the XML data through HTML, not trying to
I'm trying to insert into mysql but it giving me an error, here my
I am trying to center itemRenderers in a horizontal list if the number of
I have a Pig program where I am trying to compute the minimum center

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.