简体   繁体   中英

How to organize rows of a data.frame in R

I want to build a 3x3 data.frame in R by using two vectors of values: a vector of x-values (xr) and a vector of y-values (yr). xr has 3 values and yr has 9 values.

Here my example:

    xr<-c(1,2,3)
    yr<-c(4,4,4,5,5,5,6,6,6)
    db<-data.frame(x=xr,y=yr)

The resulting data.frame is as follows:

    > db
    x y
    1 4
    2 4
    3 4
    1 5
    2 5
    3 5
    1 6
    2 6
    3 6

However, I would like the data.frame to be like this:

    > db
    x y
    1 4
    1 4
    1 4
    2 5
    2 5
    2 5
    3 6
    3 6
    3 6

The trivial way to do it would be to use another xr, with the explicit sequence of values of x, like this:

    xr<-c(1,2,3,1,2,3,1,2,3)    

However I am looking for a way of creating such data.frame by using the same xr as in my first example.

Any help is much appreciated!

It is just a matter of the each argument of the rep function. It does exactly what its name might suggest.

db<-data.frame(x= rep(xr, each = 3) ,y=yr)
 db
  x y
1 1 4
2 1 4
3 1 4
4 2 5
5 2 5
6 2 5
7 3 6
8 3 6
9 3 6

To capture any possible differences in run-lengths, along with rep() you might want rle()

data.frame(x = rep(xr, rle(yr)$lengths), y = yr)

To show what I mean, take zr as follows. It has varying run-lengths (ie they are not all 3).

zr <- c(4, 4, 4, 5, 5, 6)
data.frame(x = rep(xr, rle(zr)$lengths), z = zr)
#   x z
# 1 1 4
# 2 1 4
# 3 1 4
# 4 2 5
# 5 2 5
# 6 3 6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM