arrays - Make a matrix of s columns of a dataframe with same column names -


how make matrix p containing proportions p1 ps s variables initial dataframe (which contains columns p1 ps)

this r problem. have dataframe includes variables p1 ps other variables. want transfer values variables p1 ps dataframe matrix p use in other routines. can readily when know number of columns s (s = 5 in example supplied below) using code below (test data in dataframe all_test 5 column example).

the following code reads in 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 solution works when based on known value 5 of s, number of columns wish transfer matrix p.

i want develop code supply ‘s’ return s columns in matrix p. code kindly supplied in first response post gives me list contains names p1 ps not see how use extract columns
p1 p5 dataframe.

i know trivial cannot sort it.

i have tried (all of gives strings of p1 ps)

s <- 5 nam1 <- paste("p", 1:s, sep = "", collapse = ", ")       nam1   # returns "p1, p2, p3, p4, p5" cat(nam1, "\n") # returns p1, p2, p3, p4, p5 not work in  p <- with(all, cbind(cat(nam1, "\n"))) 

i think see you're trying do... you've tried creates 1 string of s labels, rather list of length s.

how about: with(all, paste("p",as.character(seq(1,s)),sep=""))

edit

with updated question you've got data frame want take subset of columns , create matrix out of, that's how i'd go building expression (someone feel free tell me better way of doing this!)

subset data frame (using code posted before vector %in test):

temp<-all_test[,colnames(all_test)%in%paste("p",as.character(seq(1,s)),sep="")]

then create matrix that:

p <- data.matrix(temp)

naturally there's nothing stopping combining of into:

p <-data.matrix(all_test[,colnames(all_test)%in%paste("p",as.character(seq(1,s)),sep="")])

hope helps!


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -