1
votes

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!

1
Please, try to create a Minimal, Complete, and Verifiable example. Post a sample of your data or create an example, and show us what you already tried.Paulo MiraMor
You should share a reproducible example, with sample input and expected output format.tushaR

1 Answers

1
votes

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