1

I have a data frame like:

df

    group group_name      value
1       1       <NA>     VV0001
2       1       <NA> VV_RS00280
3       2       <NA>     VV0002
4       2       <NA> VV_RS00285
5       3       <NA>     VV0003
6       3       <NA> VV_RS00290
7       5       <NA>     VV0004
8       5       <NA> VV_RS00295
9       6       <NA>     VV0005
10      6       <NA> VV_RS00300
11      7       <NA>     VV0006
12      7       <NA> VV_RS00305
13      8       <NA>     VV0007
14      8       <NA> VV_RS00310
15      9       <NA>     VV0009
16      9       <NA> VV_RS00315
17     10       <NA>     VV0011
18     10       <NA> VV_RS00320
19     11       <NA>     VV0012
20     11       <NA> VV_RS00325
21     12       <NA>     VV0013
22     12       <NA> VV_RS00330

so I want to construct an other data frame using the columns "group" and "value", all the group 1 (df[df$group == 1,]) will get the data in "value" column (VV0001, VV_RS00280) and construct the data.frame like:

   group  value
1  VV0001 VV_RS00280

and then the next df[df$group == 2,], and so on, at the end will be:

   group  value
1  VV0001 VV_RS00280
2  VV0002 VV_RS00285
3  VV0003 VV_RS00290
4  VV0004 VV_RS00295

I tried to do it manually but the nrow(df) is big, > 3000 or more !!

Thanks

1 Answer 1

4

You may try,

library(dplyr)
library(tidyr)

df %>%
  rename(idv = group) %>%
  mutate(group_name = rep(c("group", "value"),n()/2)) %>%
  group_by(idv) %>%
  pivot_wider(names_from = group_name, values_from = value) %>%
  ungroup %>%
  select(-idv)

   group  value     
   <chr>  <chr>     
 1 VV0001 VV_RS00280
 2 VV0002 VV_RS00285
 3 VV0003 VV_RS00290
 4 VV0004 VV_RS00295
 5 VV0005 VV_RS00300
 6 VV0006 VV_RS00305
 7 VV0007 VV_RS00310
 8 VV0009 VV_RS00315
 9 VV0011 VV_RS00320
10 VV0012 VV_RS00325
11 VV0013 VV_RS00330
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.