Skip to content

Instantly share code, notes, and snippets.

@aagarw30
Created January 11, 2016 15:09
Show Gist options
  • Save aagarw30/c3db6c5cf45a608afc49 to your computer and use it in GitHub Desktop.
Save aagarw30/c3db6c5cf45a608afc49 to your computer and use it in GitHub Desktop.
Mutate demo example code snippet
# Demonstrate how to use mutate to add a new variable (called average in this demo example) into dataframe which contains the results of a function (average or mean in this demo example) performed on each row of the specified variables in the dataframe.
library(dplyr)
# create a dummy dataframe for demostration purpose
mydata = data.frame(x=c("99.15%", "98.75%", "99.52%"),y=c("96.25%", "91.55%", NA), z=c("90.10%", NA, "87.50%"))
# look at the data
str(mydata)
# we want the variable not to be factor
mydata$x = as.character(mydata$x)
mydata$y = as.character(mydata$y)
mydata$z = as.character(mydata$z)
# look at the data
str(mydata)
# remove the percentage sign from the variables x, y and z
mydata$x=as.numeric(gsub("%", " ", mydata$x))
mydata$y=as.numeric(gsub("%", " ", mydata$y))
mydata$z=as.numeric(gsub("%", " ", mydata$z))
# look at the data
str(mydata)
# applying mutate function
mydata1 = mydata %>% rowwise() %>% mutate(Average = mean(c(x, y, z), na.rm=TRUE))
# look at the resultant data
str(mydata1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment