user1478335
user1478335

Reputation: 1839

random data in a data frame:difficulty in creating

I thought that I at least understood how to form a data frame, but I cannot solve my problem. I want to create a data frame with columns names of ID, Col1 to 5 and populate each row with, in this instance, an ID number 759 to 755 and five randomly chosen numbers between 1 and 9. So something like:

ID  N1  N2  N3  N4  N5  
759  2  7   1   5   3  
758  3  7   9   8   2  
.   .   .

I have tried various ways, but either get a change in the column names or an error in the number of columns compared with the vector. My latest "effort"

df<- data.frame(row.names =NULL)
df[1,] <-c(759, sample(1:9, 5)
colnames(df) = c("ID","N1", "N2", "N3", "N4", "N5")

Eventually I want to iterate through the data and work out which data point occurred when and how long ago. ID could be replaced with a date. I am totally new to R and totally illogical in thought(!),so all help is gratefully received. I cannot find an answer on the site to clear up my confusion.

Upvotes: 1

Views: 62

Answers (2)

J.R.
J.R.

Reputation: 3888

You could always do something like:

df <- cbind( 759:755, t(replicate(5, sample(1:9, 5))))
df <- as.data.frame( df )
colnames(df) = c("ID", paste0("N",1:5) )
   ID N1 N2 N3 N4 N5
1 759  6  8  5  3  2
2 758  4  2  3  1  6
3 757  5  7  4  8  3
4 756  5  2  4  6  3
5 755  6  2  8  4  1

you should probably take a look at the difference between sample(1:9, 5) and sample(1:9, 5, replace = TRUE)

Upvotes: 2

talat
talat

Reputation: 70266

Like this?

cbind(ID = 759:755, as.data.frame(matrix(sample(1:9, 5*5, replace = TRUE), ncol = 5)))
   ID V1 V2 V3 V4 V5
1 759  5  5  6  3  9
2 758  3  4  1  4  7
3 757  2  3  7  2  5
4 756  1  2  3  6  2
5 755  9  9  8  7  8

Upvotes: 0

Related Questions