-
Notifications
You must be signed in to change notification settings - Fork 23
R tips
For anyone who is more familiar with MATLAB than with R, this website lists the R equivalents of common MATLAB commands:
There are a couple ways to do this. One is to use the () and \1, \2 type syntax in gsub() to cleverly replace an entire line with just the stuff you're interested in.
Another is to make use of the output of gregexpr(), which tells where a match is found. You can do this by using the additional function regmatches().
E.g.,
x <- c("A and B", "A, B and C", "A, B, C and D", "foobar")
pattern <- \"\[\[:space:\]\]*(,|and)\[\[:space:\]\]\"
m <- gregexpr(pattern, x)
regmatches(x, m)
To combine plots, use the par( ) function with the following two options:
- mfrow = c(n, m): Create a matrix of n rows by m columns in which the plots are filled by row
- mfcol = c(n, m): Create a matrix of n rows by m columns in which the plots are filled by column
e.g.
w <- rnorm(100); x <- rnorm(100); y <- rnorm(100); z <- rnorm(100)
par(mfrow=c(2,2)) # Create 2 x 2 matrix to fill 4 plots
plot(w, x, main = "w vs x")
plot(x, y, main = "x vs y")
plot(y, z, main = "y vs z")
plot(z, w, main = "z vs w")
Sometimes it is easier to work on data when it is not in a list, especially if you are using a function that only works on vectors, or if you have a lot of user-created functions. But if you are using lists to store data, the "format" of the list, such as the length of each element, is often an important part of the data that is ordinarily lost when a list is coerced to a vector. By using relist() you can take data and turn it back into a list of the same format of the list in the skeleton argument. This is useful for confusing nested lists, lists that use the $ operator to access certain attributes, and for functions that don't work on lists like optim.
e.g.
x<-vector(mode="list",length=10) #create empty list of length 10
x<-lapply(x,function(x) x<-rexp(sample(1:5,1),rate=1)) #individual elements in list of differing length
sapply(x,length) #check the length
y<-unlist(x) #make the list x into a vector y
length(y) #y is now a vector
y<-(y-mean(y))/sd(y) #preform some manipulation on y (just for example we standardize it)
y<-relist(flesh=y,skeleton=x) #now relist y using the "format" of x
sapply(x,length) == sapply(y,length) #check to make sure the two lists have the same "format"