1

Here is a sample of my data

code    group     type  outcome
  11        A      red      M*P
  11        N   orange      N*P
  11        Z      red        R
  12     AB A     blue      Z*P
  12     AN B    green      Q*P
  12     AA A     gray       AB

which can be created by:

df <- data.frame(
    code  = c(rep(11,3), rep(12,3)),
    group = c("A", "N", "Z", "AB A", "AN B", "AA A"),
    type  = c("red", "orange", "red", "blue", "green", "gray"),
    outcome = c("M*P", "N*P", "R", "Z*P", "Q*P", "AB"),
    stringsAsFactors = FALSE
)

I want to get the following table

code    group1  group2  group3  type1    type2  type3   outcome
  11         A       N       Z    red   orange     red      MNR
  12      AB A    AN B    AA A   blue    green    gray     ZQAB

I have used the following code, but it does not work. I want to remove Ps in outcome. Thanks for your help.

dcast(df, formula= code +group ~ type, value.var = 'outcome')
DanY
  • 5,920
  • 1
  • 13
  • 33
user3546966
  • 25
  • 1
  • 9
  • 2
    Please share sample of your data using `dput()` (not `str` or `head` or picture/screenshot) so others can help. See more here https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example?rq=1 – Tung Aug 14 '18 at 16:11

1 Answers1

3

Using data.table to hit your expected output:

library(data.table)
setDT(df)
# Clean out the Ps before hand
df[, outcome := gsub("*P", "", outcome, fixed = TRUE)]
# dcast but lets leave the outcome for later... (easier)
wdf <- dcast(df, code ~ rowid(code), value.var = c('group', 'type'))
# Now outcome maneuvering separately by code and merge
merge(wdf, df[, .(outcome = paste(outcome, collapse = "")), code])

   code group_1 group_2 group_3 type_1 type_2 type_3 outcome
1:   11       A       N       Z    red orange    red     MNR
2:   12    AB A    AN B    AA A   blue  green   gray    ZQAB
s_baldur
  • 29,441
  • 4
  • 36
  • 69
  • You taught me something new with the `fixed` argument -- much easier than remembering how many backslashes are needed in "\\*P". – DanY Aug 14 '18 at 16:19
  • @DanY it also gives a speed boost so I use it whenever I don't need regex. – s_baldur Aug 14 '18 at 16:20