Skip to content

Instantly share code, notes, and snippets.

@svenhofstede-zz
Last active August 29, 2015 14:19
Show Gist options
  • Save svenhofstede-zz/f25a02e8a341ec12f461 to your computer and use it in GitHub Desktop.
Save svenhofstede-zz/f25a02e8a341ec12f461 to your computer and use it in GitHub Desktop.
R_code_snippets
# Read csv file
dfName = read.csv("file.csv")
# READ CSV FILE WITH DATATYPE DEFINED FOR A CERTAIN COLUMN s
dfName <- read.csv("file.csv",colClasses=c("date"="Date"))
# WRITE CSV FILE
write.csv(dfName, file="file.csv")
# CREATE FRAME
dfName <- data.frame(ids, dimensions)
# CREATE FRAME WITH DATE
dfName <- data.frame(ids,as.Date(dates))
# VIEW DATA
head(dfName)
view(dfName)
# ADD COLUMN TO FRAME
dfNameNew <- within(dfName, {newField = "dummy"})
# ADD COLUMN TO FRAME with IF statement
dfNameNew <- within(dfName, {newField = ifelse(actual <= target,1,0)})
# RENAME A COLUMN
rename(dfName,c("old"="new"))
# REMOVE FRAME
remove(dfName)
# GET CLASS OF VARIABLE
class(varName)
# GET CLASS OF ALL COLUMNS IN DATA FRAME
sapply(dfName, class)
# FORMAT A DATE AS YEAR-WEEK
week = format(dfName$date,format="%Y-%U")
# GROUP BY AND SUMMARIZE VALUE
ddply(dfName,.(dimension), summarize, count=sum(intVar))
# GROUP BY AND SUMMARIZE MULTIPLE VALUES
ddply(ops6,.(dimension,week),summarize,count=sum(met),missed=sum(actual>target))
# SORT COLUMN
dfName <- dfName[order(dfName$columnName),]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment