1

I have two columns: one is a numerical variable and the other is a categorical variable. How do I make it so that I have n columns for the n categories of my categorical variable and in each column is the numerical observations that belong in that category. Please help, I have tried looking it up but I cant find a function that will do the trick.

Thank you!

Victoria
  • 11
  • 1
  • 1
    Please, try to create a [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). Post a sample of your data or [create an example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example), and show us what you already tried. – Paulo MiraMor Jan 25 '17 at 18:57
  • 1
    You should share a reproducible example, with sample input and expected output format. – tushaR Jan 25 '17 at 18:58

1 Answers1

1

assuming a sample data :

df = data.frame(x = c(3,6,1,3,8,2) , y = c(letters[1:4], 'c','a'))
df
#  x y
#1 3 a
#2 6 b
#3 1 c
#4 3 d
#5 8 c
#6 2 a

df1 = data.frame(df$x* sapply(unique(df$y), function(x) as.numeric(grepl(x, df$y))))
colnames(df1) = unique(df$y)
#     a    b    c    d
#1    3    0    0    0
#2    0    6    0    0
#3    0    0    1    0
#4    0    0    0    3
#5    0    0    8    0
#6    2    0    0    0
joel.wilson
  • 8,243
  • 5
  • 28
  • 48