最も直接的なアプローチはmelt
、「reshape2」から使用することです。あなたのdata.frameが「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
アップデート
私の心は base からの結果の名前を適切に処理する方法に取り組んでいませreshape
んが、次のようなこともできます:
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
どこ:
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))