Maho Takahashi

Linguistics PhD Student at UC San Diego

research

CV

code

mtakahas[at]ucsd[dot]edu

How to spread a column in two (with and without keys)

df
##   ID                     Stimuli Category
## 1  1  This is the first question question
## 2  1    This is the first answer   answer
## 3  2 This is the second question question
## 4  2   This is the second answer   answer
## 5  3  This is the third question question
## 6  3    This is the third answer   answer

If there is a key variable like Category, we can use that in the spread function.

df %>% spread(Category, Stimuli)
##   ID                    answer                    question
## 1  1  This is the first answer  This is the first question
## 2  2 This is the second answer This is the second question
## 3  3  This is the third answer  This is the third question

When there are no key variables, you can still separate the Stimuli column as follows:

df1
##   ID                     Stimuli
## 1  1  This is the first question
## 2  1    This is the first answer
## 3  2 This is the second question
## 4  2   This is the second answer
## 5  3  This is the third question
## 6  3    This is the third answer
df1_new = as.data.frame(matrix(df1$Stimuli, ncol = 2, byrow = TRUE))
cbind(ID = unique(df1$ID), df1_new)
##   ID                          V1                        V2
## 1  1  This is the first question  This is the first answer
## 2  2 This is the second question This is the second answer
## 3  3  This is the third question  This is the third answer