I have data in an unusual format. What should be the variable names / column headings are currently row values, and what should be the row values are the variable names / column headings.
That is, I have a dataframe like this:
id <- seq(1, 5, 1)
good <- c('', 'Q4', 'Q4, Q2', '', '')
ok <- c('Q3, Q1', '', '', 'Q2', '')
bad <- c('', 'Q2', 'Q2', '', '')
data <- as.data.frame(cbind(id, good, ok, bad))
cols <- c('good', 'ok', 'bad')
data[cols] <- lapply(data[cols], as.character)
And I would like to convert it into a dataframe that looks like this:
id <- seq(1,5,1)
Q1 <- c('ok', '', '', '', '')
Q2 <- c('', 'bad', 'good, bad', 'ok', '') # Yes, it is possible to get multiple,
# conflicting responses to a question from one id.
Q3 <- c('ok', '', '', '', '')
Q4 <- c('', 'good', 'good', '', '')
data_new <- as.data.frame(cbind(id, Q1, Q2, Q3, Q4))
cols <- c('Q1', 'Q2', 'Q3', 'Q4')
data_new[cols] <- lapply(data_new[cols], as.character)
Some issues:
What are currently the row values can't just be transposed directlyto the column headings because sometimes multiple entries are recorded in a single cell and there should be only one value recorded in a column heading (e.g., I don't want a columnheading labelled 'Q2, Q4' in the updated dataframe).
On the other hand, when the column headings are moved to become row values, there will sometimes need to be multiple entries in the same cell. For example, the entry under the variable Q2 for id 3 should read 'good, bad' in the updated dataframe.
A dplyr solution is preferred but answers using other packages/base R are also welcomed.