correlation matrix with certain variables in r

To create a correlation matrix with certain variables in R, you can use the cor() function along with the subset() function.

Here's an example code snippet:

main.r
# create sample data frame
df <- data.frame(
  var1 = rnorm(100),
  var2 = rnorm(100),
  var3 = rnorm(100),
  var4 = rnorm(100)
)

# create correlation matrix with var1 and var2
corr_matrix <- cor(subset(df, select=c(var1, var2)))

# print correlation matrix
print(corr_matrix)
278 chars
14 lines

In this example, we create a sample data frame df with 4 variables. We then use subset() to select only var1 and var2, and pass that subset to the cor() function to compute the correlation matrix. Finally, we print the resulting correlation matrix.

You can modify the subset() function to include any variables you're interested in, and the resulting corr_matrix will only include correlations between those variables.

gistlibby LogSnag