HOW CAN I RESHAPE MY DATA IN R

HOW CAN I RESHAPE MY DATA IN R? | R FAQ

When there are multiple measurements of the same subject, across time or using different tools, the data is often described as being in "wide" format if there is one observation row per subject with each measurement present as a different variable and "long" format if there is one observation row per measurement (thus, multiple rows per subject). Different functions require different formats, and so the need to reshape a dataset may arise.

Below, we start with a dataset in wide format. Students have been measured using five metrics: readwritemathscience, and socst.

hsb2 <- read.table('https://stats.idre.ucla.edu/stat/r/faq/hsb2.csv', header=T, sep=",")

hsb2[1:10,]id female race ses schtyp prog read write math science socst1  70      0    4  1      1    1  57    52  41      47    572  121      1    4  2      1    3  68    59  53      63    613  86      0    4  3      1    1  44    33  54      58    314  141      0    4  3      1    3  63    44  47      53    565  172      0    4  2      1    2  47    52  57      53    616  113      0    4  2      1    2  44    52  51      63    617  50      0    3  2      1    1  50    59  42      53    618  11      0    1  2      1    2  34    46  45      39    369  84      0    4  2      1    1  63    57  54      58    5110  48      0    3  2      1    2  57    55  52      50    51

To reformat this dataset into long form, we will use the reshape function. The arguments we provide include a list of variable names that define the different times or metrics (varying), the name we wish to give the variable containing these values in our long dataset (v.names), the name we wish to give the variable describing the different times or metrics (timevar), the values this variable will have (times), and the end format for the data (direction). Additionally, we have provided new row names.

## Wide to long

l <- reshape(hsb2,

  varying = c("read", "write", "math", "science", "socst"),

  v.names = "score",

  timevar = "subj",

  times = c("read", "write", "math", "science", "socst"),

  new.row.names = 1:1000,

  direction = "long")

l.sort <- l[order(l$id),]

l.sort[1:10,]id female race ses schtyp prog    subj score99  1      1    1  1      1    3    read    34299  1      1    1  1      1    3  write    44499  1      1    1  1      1    3    math    40699  1      1    1  1      1    3 science    39899  1      1    1  1      1    3  socst    41139  2      1    1  2      1    3    read    39339  2      1    1  2      1    3  write    41539  2      1    1  2      1    3    math    33739  2      1    1  2      1    3 science    42939  2      1    1  2      1    3  socst    41

After sorting by id, we can see that we have five rows per student and their five scores appear in the score variable with the subj variable indicating which test on which the score was measured. For each of the five rows per id, the femaleracesesschtyp, and prog variables are unchanging.

We can similarly go from this long form back to our original wide form again using reshape with different arguments (most importantly, direction = "wide"). With timevar, we indicate the variable that will define the multiple measurements per subject. With idvar, we list the variables that should do not vary within subject.

## Long to wide

w <- reshape(l.sort,

  timevar = "subj",

  idvar = c("id", "female", "race", "ses", "schtyp", "prog"),

  direction = "wide")


w[1:10,]id female race ses schtyp prog score.read score.write score.math score.science score.socst99  1      1    1  1      1    3        34          44        40            39          41139  2      1    1  2      1    3        39          41        33            42          4184  3      0    1  1      1    2        63          65        48            63          56112  4      1    1  1      1    2        44          50        41            39          5176  5      0    1  1      1    2        47          40        43            45          31149  6      1    1  1      1    2        47          41        46            40          4150  7      0    1  2      1    2        57          54        59            47          5194  8      1    1  1      1    2        39          44        52            44          4860  9      0    1  2      1    3        48          49        52            44          51154 10      1    1  2      1    1        47          54        49            53          61

Once again, we have one observation per student. We can compare the dimensions of our wide dataset w to our original dataset:

dim(w)[1] 200  11dim(hsb2)[1] 200  11

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 193,812评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,626评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,144评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,052评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,925评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,035评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,461评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,150评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,413评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,501评论 2 307
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,277评论 1 325
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,159评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,528评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,868评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,143评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,407评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,615评论 2 335

推荐阅读更多精彩内容

  • 4.2 dplyr包简介 dplyr包提供了一组函数,用于有效地操作R中的数据集。dplyr包是下一代“plyr”...
    ZMQ要加油呀阅读 1,236评论 0 0
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,223评论 0 23
  • 16宿命:用概率思维提高你的胜算 以前的我是风险厌恶者,不喜欢去冒险,但是人生放弃了冒险,也就放弃了无数的可能。 ...
    yichen大刀阅读 6,014评论 0 4
  • 公元:2019年11月28日19时42分农历:二零一九年 十一月 初三日 戌时干支:己亥乙亥己巳甲戌当月节气:立冬...
    石放阅读 6,864评论 0 2
  • 昨天考过了阿里规范,心里舒坦了好多,敲代码也犹如神助。早早完成工作回家喽
    常亚星阅读 3,026评论 0 1