Essentially, I want to make a "Test Type"
column in my data frame and fill it with the 3 tests each unique row has to undergo. I want to know how to repeat each unique row and fill the new column with the specified test.
Asked
Active
Viewed 1,034 times
1
-
Please post your data using `dput()`. – tmfmnk Aug 20 '19 at 20:32
2 Answers
0
Specify the replication needed in uncount
for each row, expand the data, grouped by 'ID', create the 'TestType' as the concatenated 'Test' string with the sequence of rows (row_number()
)
library(tidyverse)
uncount(df1, 3) %>%
group_by(ID) %>%
mutate(TestType = str_c("Test", row_number(), sep=' '))
# A tibble: 12 x 5
# Groups: ID [4]
# ID Name Age State TestType
# <dbl> <chr> <dbl> <chr> <chr>
# 1 100 Bob 19 VA Test 1
# 2 100 Bob 19 VA Test 2
# 3 100 Bob 19 VA Test 3
# 4 102 Chase 12 NY Test 1
# 5 102 Chase 12 NY Test 2
# 6 102 Chase 12 NY Test 3
# 7 103 Hannah 15 CA Test 1
# 8 103 Hannah 15 CA Test 2
# 9 103 Hannah 15 CA Test 3
#10 104 Jason 19 CA Test 1
#11 104 Jason 19 CA Test 2
#12 104 Jason 19 CA Test 3
Or another option is to create a list
column and then unnest
df1 %>%
mutate(TestType = list(str_c('Test', 1:3, sep=' '))) %>%
unnest
data
df1 <- data.frame(ID = c(100, 102, 103, 104), Name = c("Bob", "Chase",
"Hannah", "Jason"), Age = c(19, 12, 15, 19),
State = c("VA", "NY", "CA", "CA"), stringsAsFactors = FALSE)

akrun
- 874,273
- 37
- 540
- 662
0
you could do:
dplyr::arrange(merge(df1,list(TestType = paste("Test",1:3))),ID)
ID Name Age State TestType
1 100 Bob 19 VA Test 1
2 100 Bob 19 VA Test 2
3 100 Bob 19 VA Test 3
4 102 Chase 12 NY Test 1
5 102 Chase 12 NY Test 2
6 102 Chase 12 NY Test 3
7 103 Hannah 15 CA Test 1
8 103 Hannah 15 CA Test 2
9 103 Hannah 15 CA Test 3
10 104 Jason 19 CA Test 1
11 104 Jason 19 CA Test 2
12 104 Jason 19 CA Test 3
or simply put you could do:
merge(df1,paste("Test",1:3))
which will give you the results but ordered with TestType
instead of ID
. You can then order
using the ID
column

Onyambu
- 67,392
- 3
- 24
- 53