简体   繁体   中英

How do I combine vectors into a dataframe using an index vector in R?

I have a dataframe df of answers to a survey (IPAQ) with 27 questions. These are the first 8 columns:

df
       ID   `1`   `2`   `3`   `4`   `5`   `6`   `7`
    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
 1    28     0     0     0     0     0     0     0
 2    52     0     0     0     0     0     0     0
 3    97     1     0     0     1    60     0     0
 4   100     0     0     0     0     0     0     0
 5   112     0     0     0     0     0     0     0
 6   157     0     0     0     0     0     0     0
 7   252     0     0     0     0     0     0     0
 8   254     1     0     0     4   120     7   180
 9   309     1     0     0     2    30     0     0
10   332     0     0     0     0     0     0     0

I have created variables which convert these answers into meaningful totals eg:

###Housework and gardening###
gard.vig = (5.5 * df$`14` * df$`15`)
gard.mod = (4.0 * df$`16` * df$`17`)
house.mod = (3.0 * df$`18` * df$`19`)
total.hg = (gard.mod + gard.vig + house.mod)

###Leisure###
lei.walk = (3.3 * df$`20` * df$`21`)
lei.mod = (4.0 * df$`24` * df$`25`)
lei.vig = (8.0 * df$`22` * df$`23`)
tot.lei = (lei.walk + lei.mod + lei.vig)

I want to combine/ bind these variables together in a dataframe/tibble using the ID variable from the original df to create something like this:

ID lei.walk lei.mod lei.vig total.lei gard.mod gard.vig etc.
28 600      55      89      etc.
52 etc. 
etc.

Since the vector are already calculated we can directly cbind them

cbind(df[1], gard.vig, gard.mod, house.mod, total.hg, lei.walk, 
             lei.mod, lei.vig, tot.lei)

Or using data.frame

data.frame(ID = df$ID, gard.vig, gard.mod, house.mod, total.hg,
                lei.walk,lei.mod, lei.vig, tot.lei)

We can use tibble

library(tibble)
tibble(df[1],  gard.vig, gard.mod, house.mod, total.hg, lei.walk, 
         lei.mod, lei.vig, tot.lei)

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