user330
user330

Reputation: 1290

How to sort a a specific column out in R

I want to get the table below for the column O

  

  BB    K   C   O   P
    1   1   c1  o1  4
    2   1   c2  o1  1
    3   1   c3  o1  8
    4   1   c4  o2  3
    5   1   c5  o2  4
    6   1   c6  o2  9
    7   2   c1  o1  2
    8   2   c2  o1  1
    9   2   c3  o1  3
    10  2   c4  o2  8
    11  2   c5  o2  7
    12  2   c6  o2  9
    13  3   c1  o1  6
    14  3   c2  o1  10
    15  3   c3  o1  6
    16  3   c4  o2  2
    17  3   c5  o2  9
    18  3   c6  o2  5

The codes used are :

tibble(BB= c(1:18)) %>% 
    group_by(K= factor(rep(row_number(), each=6, length.out = n()))) %>% 
    mutate(C = str_c('c', row_number())) %>% 
    group_by(O= factor(rep(row_number(), each=2, length.out = n()))) %>% 
    mutate(P = sample(1:10, n(), replace = TRUE)) %>% 
ungroup

I struggle to sort out the column O

Upvotes: 0

Views: 45

Answers (2)

C Jeruzal
C Jeruzal

Reputation: 548

user330, Here is another way to build your tibble:

# Load Libraries
library('tidyverse')

# Set up Tibble
df <- tibble(BB = seq(1:18)) %>% 
  mutate(K = rep(1:3, each=6)) %>% 
  mutate(C = rep(paste0("c",seq(1:6),sep=""), times = 3)) %>% 
  mutate(O = rep(paste0("o",seq(1:2),sep=""), each = 3, times = 3)) %>% 
  mutate(P = sample(1:10, n(), replace = TRUE))

# Check results
df
#> # A tibble: 18 x 5
#>       BB     K C     O         P
#>    <int> <int> <chr> <chr> <int>
#>  1     1     1 c1    o1       10
#>  2     2     1 c2    o1        2
#>  3     3     1 c3    o1        8
#>  4     4     1 c4    o2        8
#>  5     5     1 c5    o2       10
#>  6     6     1 c6    o2        1
#>  7     7     2 c1    o1        1
#>  8     8     2 c2    o1        9
#>  9     9     2 c3    o1        4
#> 10    10     2 c4    o2        9
#> 11    11     2 c5    o2        7
#> 12    12     2 c6    o2        3
#> 13    13     3 c1    o1        3
#> 14    14     3 c2    o1       10
#> 15    15     3 c3    o1        3
#> 16    16     3 c4    o2        7
#> 17    17     3 c5    o2        4
#> 18    18     3 c6    o2        5

Upvotes: 1

Ronak Shah
Ronak Shah

Reputation: 389235

We can use rep :

library(dplyr)

df %>%
  group_by(K) %>%
  mutate(O = rep(c('o1', 'o2'), each = n()/2, length.out = n()))

#      BB K     C     O         P
#   <int> <fct> <chr> <chr> <int>
# 1     1 1     c1    o1        8
# 2     2 1     c2    o1        6
# 3     3 1     c3    o1        2
# 4     4 1     c4    o2       10
# 5     5 1     c5    o2       10
# 6     6 1     c6    o2        9
# 7     7 2     c1    o1        9
# 8     8 2     c2    o1        3
# 9     9 2     c3    o1        2
#10    10 2     c4    o2        6
#11    11 2     c5    o2        9
#12    12 2     c6    o2        3
#13    13 3     c1    o1        8
#14    14 3     c2    o1        1
#15    15 3     c3    o1        2
#16    16 3     c4    o2        2
#17    17 3     c5    o2        7
#18    18 3     c6    o2        5

Upvotes: 1

Related Questions