Skip to content

create matrix

4 messages · Felix Zajitschek - UNSW, jim holtman, Simon Blomberg +1 more

#
Since you did not provide a sample of your data, here is an example of
how to take a vector and create a matrix with 5 entries for each
value, with the extra ones having a zero in the second column:
x
1 2 3 4 5 6 7
2 4 3 2 4 4 1
+     # pad with at least 5 extra rows to make sure matrix is filled out
+     z <- cbind(c(.val, rep(.val[1],5)), c(rep(1, length(.val)), rep(0,5)))
+     z[1:5,]   # only return the first 5
+ })
[,1] [,2]
 [1,]    1    1
 [2,]    1    1
 [3,]    1    0
 [4,]    1    0
 [5,]    1    0
 [6,]    2    1
 [7,]    2    1
 [8,]    2    1
 [9,]    2    1
[10,]    2    0
[11,]    3    1
[12,]    3    1
[13,]    3    1
[14,]    3    0
[15,]    3    0
[16,]    4    1
[17,]    4    1
[18,]    4    0
[19,]    4    0
[20,]    4    0
[21,]    5    1
[22,]    5    1
[23,]    5    1
[24,]    5    1
[25,]    5    0
[26,]    6    1
[27,]    6    1
[28,]    6    1
[29,]    6    1
[30,]    6    0
[31,]    7    1
[32,]    7    0
[33,]    7    0
[34,]    7    0
[35,]    7    0
On Thu, Mar 20, 2008 at 1:51 AM, Felix Zajitschek - UNSW
<felix.zajitschek at unsw.edu.au> wrote:

  
    
#
It depends on how you have your data laid out.  This
is clumsy but I think it will work.  There should be
an easier way than a loop but I don't see it.  People
with more experience in R will likely have much better
solutions.

In any case it sure beats Excel or any other
spreadsheet :)
======================================================

# Create mock data set (data.frame) with four cows.  
i <- 1:4
cows <- paste("cow",i, sep="")
food <- sample(c("hay", "grain"), 4, replace=TRUE)
cattle <- data.frame(cows, food)

# Vecctor of longevity data
age <- sample(3:9, 4, replace = TRUE)

#Create empty list
mylist <- NULL

for(i in 1:length(cattle[,1])) {
count <-(seq(1,age[i]))
dead <- c(rep(0,length(count)-1),1)
newcow <- data.frame(merge(data.frame(cattle[i,]),
count),dead)
mylist[[i]] <- newcow
}

# Turn mylist into a data.frame
mydata  <- do.call(rbind, mylist)

# Get rid of unneeded count varable.
mydata <- mydata[,-3]
mydata

======================================================
--- Felix Zajitschek - UNSW
<felix.zajitschek at unsw.edu.au> wrote:

            
______________________________________________________________
<http://www.bees.unsw.edu.au/school/researchstudents/zajitschekfelix.htm
www.bees.unsw.edu.au/school/researchstudents/zajitschekfelix.html
[[elided trailing spam]]