Sistema de blogs Diarium
Universidad de Salamanca
Statistics and R software
Blog by JMSS
 

R pill: “Enter a vector or matrix in the R console using the keyboard”

When we have few numerical data, either in a small vector or in a matrix of small dimensions, we can create a “vector” or “matrix” object in the R working environment using the “scan ()” function and entering the data with the keyboard on the R console.

Examples:
* foo1() is a function that asks for the size of the vector and each of its components. Run the code and try to enter the vector (3,6,7,1,-4,9). Then plot the vector.

* foo2() is a function that asks for the dimensions of the matrix, the labels of rows and columns and finally each of its components, that must be entered by columns. Run the code, try to enter the matrix and then summarize it with the summary() function.
_x y
a 1 3
b 5 7
c 4 0

# Vector
foo1 <- function() {
cat("What is the size of the numerical vector? ", "\n")
size <- scan("", nmax = 1)
cat("Enter each component of the vector: ", "\n")
temp <- c(scan("", nmax = size))
print(temp)
return(temp)
}
vec <- foo1()
# plot the vector
plot(vec)

# Matrix
foo2 <- function() {
cat("Number of rows of the numerical matrix:", "\n")
rows = scan("", n = 1)
cat("Number of columns of the numerical matrix:", "\n")
cols = scan("", n = 1)
cat("Enter each row label", "\n")
nom_rows = c(scan("", n = rows, what = "character"))
cat("Enter each column label", "\n")
nom_cols = c(scan("", n = cols, what = "character"))
cat("Enter each component of the matrix by columns", "\n")
temp <- matrix(scan("", n = rows * cols), nrow = rows, ncol = cols,
dimnames = list(nom_rows, nom_cols)
)
return(temp)
}
m <- foo2()
# view the matrix
m
# summarize the matrix
summary(m)

 —

jose

About jose

Profesor titular del Dpto. de Estadística e I.O. de la Usal. Entusiasta del software estadístico R.
Aún no hay comentarios.

Deja un comentario

Política de privacidad
Studii Salmantini. Campus de excelencia internacional