How to make a matrix P containing the proportions p1 to ps for s variables from the initial dataframe (which contains columns p1 to ps)
This is an R problem. I have a dataframe that includes variables p1 to ps as well as other variables. I want to transfer the values for variables p1 to ps from the dataframe to a matrix P for use in other routines. I can readily do this when I know the number of columns s (s = 5 in the example supplied below) using the code below (test data is in dataframe ALL_test for a five column example).
The following code reads in the example dataframe ALL_test.
ALL_test <- data.frame(
x = c(50,75,45), p1 = c(1, 0, 0), p2 = c(0, .4, .1), p3 = c(0, .2, .3),
p4 = c(0, .4, .1), p5 = c(0, 0, .5)
)
P <- with(ALL_test, cbind(p1, p2, p3, p4, p5))
colnames(P)<- c("p1","p2","p3","p4","p5")
Outputting P shows that this solution works when based on the known value 5 of s, the number of columns I wish to transfer to a matrix P.
I want to develop code where I supply āsā that will return
s columns in the matrix P. The code that was kindly supplied in the
first response to this post gives me a list that contains the names
p1 to ps but I do not see how to use this to extract the columns
p1 to p5 from the dataframe.
I know that this is probably trivial but I cannot sort it.
I have tried (all of which just gives strings of p1 to ps)
s <- 5
nam1 <- paste("p", 1:s, sep = "", collapse = ", ")
nam1 # this returns "p1, p2, p3, p4, p5"
cat(nam1, "\n") # returns p1, p2, p3, p4, p5 but this does not work in
P <- with(ALL, cbind(cat(nam1, "\n")))