The most direct approach is to use melt
from "reshape2". Assuming your data.frame is called "mydf":
> library(reshape2)
> melt(mydf, id.vars=1:2)
Question Year variable value
1 1 1999 CountryA Yes
2 2 1999 CountryA Yes
3 1 1999 CountryB No
4 2 1999 CountryB Yes
5 1 1999 CountryZ No
6 2 1999 CountryZ Yes
Update
My mind's not working on how to properly deal with the resulting names from base reshape
, but you can also do something like this:
names(mydf) <- sub("Country", "Country.", names(mydf))
setNames(
reshape(mydf, direction="long", idvar=1:2, varying=3:ncol(mydf)),
c("Question", "Year", "Country", "Answer"))
# Question Year Country Answer
# 1.1999.A 1 1999 A Yes
# 2.1999.A 2 1999 A Yes
# 1.1999.B 1 1999 B No
# 2.1999.B 2 1999 B Yes
# 1.1999.Z 1 1999 Z No
# 2.1999.Z 2 1999 Z Yes
Where:
mydf <- structure(list(Question = 1:2, Year = c(1999L, 1999L), CountryA = c("Yes",
"Yes"), CountryB = c("No", "Yes"), CountryZ = c("No", "Yes")), .Names = c("Question",
"Year", "CountryA", "CountryB", "CountryZ"), class = "data.frame", row.names = c(NA, -2L))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…