将R列名转换为id变量
我很困惑,甚至没能找到我要找的东西。我有一个针对不同国家的多年调查,目前是这样的:将R列名转换为id变量,r,reshape,R,Reshape,我很困惑,甚至没能找到我要找的东西。我有一个针对不同国家的多年调查,目前是这样的: Question Year CountryA CountryB ... CountryZ 1 1999 Yes No No 2 1999 Yes Yes Yes 问题年份CountryA CountryB。。。CountryZ 1 1999是
Question Year CountryA CountryB ... CountryZ 1 1999 Yes No No 2 1999 Yes Yes Yes 问题年份CountryA CountryB。。。CountryZ 1 1999是否否 1999年2月是的是的 也就是说,它目前是按问题组织的。我想按国家、年份和问题编号排列数据:
Country Year Question Answer A 1999 1 Yes A 1999 2 Yes B 1999 1 No B 1999 2 Yes 国家年问题答案 A 1999年1月1日是 A 1999年2月,是的 B 1999年第1号 B 1999 2是的
等等这可能吗?我似乎找不到任何东西来引导我找到正确的答案。
提前谢谢 最直接的方法是使用“重塑2”中的
melt
。假设您的data.frame名为“mydf”:
使现代化 我的脑子里并没有想着如何正确处理base
restrape
中生成的名称,但您也可以这样做:
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
names(mydf)最直接的方法是使用“重塑2”中的melt
。假设您的data.frame名为“mydf”:
使现代化
我的脑子里并没有想着如何正确处理baserestrape
中生成的名称,但您也可以这样做:
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
遵循@Ananda方法的名称(mydf)
DF <- read.table(text="Question \t Year CountryA CountryB CountryZ
1 1999 Yes No No
2 1999 Yes Yes Yes", sep="\t", header=T)
> DF
Question Year CountryA CountryB CountryZ
1 1 1999 Yes No No
2 2 1999 Yes Yes Yes
DF <- melt(DF, id.vars=1:2, value.name="Answer", variable.name="Country")
> DF
Question Year Country Answer
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
DF
问题年份CountryA CountryB CountryZ
1 1999年1月1日是否
2 1999年2月是的是的
DF-DF
问题年份国家答案
1 1999年11月a是
2 1999年2月a是
3.1 1999年国家B号
4.2 1999国家B是的
5.1 1999年国家Z号
6.2 1999 CountryZ是的
然后,只需按照@Ananda的方法更改国家栏的级别…
DF <- read.table(text="Question \t Year CountryA CountryB CountryZ
1 1999 Yes No No
2 1999 Yes Yes Yes", sep="\t", header=T)
> DF
Question Year CountryA CountryB CountryZ
1 1 1999 Yes No No
2 2 1999 Yes Yes Yes
DF <- melt(DF, id.vars=1:2, value.name="Answer", variable.name="Country")
> DF
Question Year Country Answer
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
DF
问题年份CountryA CountryB CountryZ
1 1999年1月1日是否
2 1999年2月是的是的
DF-DF
问题年份国家答案
1 1999年11月a是
2 1999年2月a是
3.1 1999年国家B号
4.2 1999国家B是的
5.1 1999年国家Z号
6.2 1999 CountryZ是的
然后,这只是一个改变国家栏级别的问题