Skip to content

Instantly share code, notes, and snippets.

@drbenvincent
Created June 13, 2016 11:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save drbenvincent/016ca3c717994f72e7cb7cec373b361e to your computer and use it in GitHub Desktop.
Save drbenvincent/016ca3c717994f72e7cb7cec373b361e to your computer and use it in GitHub Desktop.
multiple groups of row means in R
# We have a dataframe with many columns.
# 15 of these columns correspond to responses to questions about hunger.
# They group into 5 subscales (each with 3 questions).
# I want to calculate these subscales (means) as well as an overall score (mean of all).
# This then needs to applied to the control condition (C) and a fasted condition (F) scores
# Once the means are calculated I no longer need the raw scores, so bonus is to automatically remove these columns. Need to retain all other columns in orginal dataframe.
# The code below works just fine, but seems pretty verbose. Is there a more R-like, concise way to do this?
# It seems like a split-apply-combine, but applied to columns rather than rows?
rawdata$C.hunger1 <- apply(rawdata[,c('CQ1.1', 'CQ1.2', 'CQ1.3')], 1, function(x) mean(x) )
rawdata$C.hunger2 <- apply(rawdata[,c('CQ2.1', 'CQ2.2', 'CQ2.3')], 1, function(x) mean(x) )
rawdata$C.hunger3 <- apply(rawdata[,c('CQ3.1', 'CQ3.2', 'CQ3.3')], 1, function(x) mean(x) )
rawdata$C.hunger4 <- apply(rawdata[,c('CQ4.1', 'CQ4.2', 'CQ4.3')], 1, function(x) mean(x) )
rawdata$C.hunger5 <- apply(rawdata[,c('CQ5.1', 'CQ5.2', 'CQ5.3')], 1, function(x) mean(x) )
rawdata$C.hunger <- apply(rawdata[,c('C.hunger1', 'C.hunger2', 'C.hunger3', 'C.hunger4', 'C.hunger5')], 1, function(x) mean(x) )
# repeat this process for the fasting (F) condition
rawdata$F.hunger1 <- apply(rawdata[,c('FQ1.1', 'FQ1.2', 'FQ1.3')], 1, function(x) mean(x) )
rawdata$F.hunger2 <- apply(rawdata[,c('FQ2.1', 'FQ2.2', 'FQ2.3')], 1, function(x) mean(x) )
rawdata$F.hunger3 <- apply(rawdata[,c('FQ3.1', 'FQ3.2', 'FQ3.3')], 1, function(x) mean(x) )
rawdata$F.hunger4 <- apply(rawdata[,c('FQ4.1', 'FQ4.2', 'FQ4.3')], 1, function(x) mean(x) )
rawdata$F.hunger5 <- apply(rawdata[,c('FQ5.1', 'FQ5.2', 'FQ5.3')], 1, function(x) mean(x) )
rawdata$F.hunger <- apply(rawdata[,c('F.hunger1', 'F.hunger2', 'F.hunger3', 'F.hunger4', 'F.hunger5')], 1, function(x) mean(x) )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment