将R列名转换为id变量 [英] Converting R Column names into id variables

查看:13
本文介绍了将R列名转换为id变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我非常困惑,甚至无法搜索到我要查找的内容。我有一个对不同国家的多年调查,目前是这样的:

        Question  Year  CountryA  CountryB  ...  CountryZ
        1         1999       Yes        No             No 
        2         1999       Yes        Yes            Yes

也就是,它目前是按问题组织的。我希望按国家/地区、年份和问题编号排列数据:

Country  Year  Question  Answer
      A  1999         1     Yes
      A  1999         2     Yes
      B  1999         1      No
      B  1999         2     Yes

诸若此类。这有可能吗?我似乎找不到任何可以引导我找到正确答案的东西。
提前感谢!

推荐答案

最直接的方法是使用"reshape2"中的melt。假设您的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

更新

我不知道如何正确处理从basereshape产生的名称,但您也可以这样做:

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))

这篇关于将R列名转换为id变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆