R:如何从一列中增加多余的行?

时间:2019-01-01 21:01:18

标签: r dataframe

我有一个人类手的数据集,目前将一个人定义为一个观察值。我想重塑数据框以将手作为单独的观察结果。我尝试使用“ dplyr”软件包和“ gather”功能进行操作,但没有成功。

因此,每个人都排成一行:

id Gender Age   Present_R    Present_L    Dominant
1    F     2      TRUE         TRUE          R
2    F     5      TRUE         FALSE         L
3    M     8      FALSE        FALSE         R

为此,每只手在一行上:

id Gender Age   Hand    Present  Dominant
1    F     2     R       TRUE     TRUE
2    F     2     L       TRUE     FALSE
3    F     5     R       TRUE     FALSE
4    F     5     L       FALSE    TRUE
5    M     8     R       FALSE    TRUE
6    M     8     L       FALSE    FALSE

请注意,手的优势变得合乎逻辑。

2 个答案:

答案 0 :(得分:5)

我们可以将"use strict"; function Shape(id, name, color) { this.id = id; this.name = name; this.color = color; }; Shape.prototype.getDisplayName = function() { return this.id + ":" + this.name; } Circle.prototype = Object.create(Shape.prototype); Circle.prototype.constructor = Circle; function Circle(id, name, color, radius) { Shape.call(this, id, name, color); this.radius = radius; }; let circle1 = new Circle('id1', 'Circle', 'red', 5); let circle2 = new Circle('id3', 'Circle', 'blue', 12); let shapes = [circle1, circle2]; for (let shape in shapes) { console.log(shapes[shape].getDisplayName()); }转换为'long'格式,通过'id'gather,然后通过arrange将'Present'列的'Hand'移除来创建'Dominant' “手”列的子字符串

unlist

基于OP的注释,看来我们需要将“优势”与“手形”进行比较

library(tidyverse)
gather(df1, Hand, Present, Present_R:Present_L) %>%
   arrange(id) %>%
   mutate(Dominant = unlist(df1[c("Present_L", "Present_R")]),
          id = row_number(),
          Hand = str_remove(Hand, ".*_"))
#   id Gender Age Dominant Hand Present
#1  1      F   2     TRUE    R    TRUE
#2  2      F   2    FALSE    L    TRUE
#3  3      F   5    FALSE    R    TRUE
#4  4      F   5     TRUE    L   FALSE
#5  5      M   8     TRUE    R   FALSE
#6  6      M   8    FALSE    L   FALSE

答案 1 :(得分:0)

对于较小的数据帧(即,无论情况如何,变量都很少),“手动编码”可能是最简单的方法:

with(df, data.frame(id = c(id,id), Gender=c(Gender,Gender), Age=c(Age, Age), 
                    Hand = c(rep("R", nrow(df)), rep("L", nrow(df))),
                    Present = c(Present_R, Present_L),
                    Dominant = c(Dominant=="R", Dominant=="L")
                    ))