R | Data Creation

Ever wonder how to generate data within R?

  • c(…) generic function to combine arguments with the default forming a vector; with recursive=TRUE descends through lists combining all elements into one vector
  • from:to generates a sequence; “:” has operator priority; 1:4 + 1 is “2,3,4,5”
  • seq(from,to) generates a sequence by= specifies increment; length=specifies desired length
  • seq(along=x) generates 1, 2, …, length(along); useful for for loops
  • rep(x,times) replicate x times; use each= to repeat “each” element of x each times; rep(c(1,2,3),2) is 1 2 3 1 2 3;
  • rep(c(1,2,3),each=2) is 1 1 2 2 3 3
  • data.frame(…) create a data frame of the named or unnamed arguments; data.frame(v=1:4,ch=c(“a”,”B”,”c”,”d”),n=10);
  • shorter vectors are recycled to the length of the longest
  • list(…) create a list of the named or unnamed arguments; list(a=c(1,2),b=”hi”,c=3i);
  • array(x,dim=) array with data x; specify dimensions like dim=c(3,4,2); elements of x recycle if x is not long enough
  • matrix(x,nrow=,ncol=) matrix; elements of x recycle
  • factor(x,levels=) encodes a vector x as a factor
  • gl(n,k,length=n*k,labels=1:n) generate levels (factors) by specifying the pattern of their levels; k is the number of levels, and n is the number of replications expand.grid() a data frame from all combinations of the supplied vectors or factors
  • rbind(…) combine arguments by rows for matrices, data frames, and others
  • cbind(…) id. by columns

Please note: I reserve the right to delete comments that are offensive or off-topic.

Leave a Reply

Your email address will not be published. Required fields are marked *