R:如何从列中添加额外的行?

use*_*713 3 r dataframe

我有一个人手的数据集,目前单个人被定义为单个观察.我想重塑数据帧以将手作为单独的观察.我尝试了"dplyr"包和"聚集"功能,但根本没有成功.

所以,从这里,每个人都在一排:

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
Run Code Online (Sandbox Code Playgroud)

对此,每只手都在一排:

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
Run Code Online (Sandbox Code Playgroud)

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

akr*_*run 5

我们可以通过'id' gather进入'long'格式,arrange然后通过unlist'Present'列创建'Dominant',通过删除'Hand'列的子字符串'Hand'

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
Run Code Online (Sandbox Code Playgroud)

基于OP的评论,似乎我们需要将'Dominant'与'Hand'进行比较

gather(df1, Hand, Present, Present_R:Present_L) %>%
    arrange(id) %>% 
    mutate(id = row_number(),
           Hand = str_remove(Hand, ".*_"),
           Dominant = Dominant == 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
Run Code Online (Sandbox Code Playgroud)

  • @NelsonGon谢谢.对我来说,我最初检查预期的输出.但是现在,通过查看OP所做的评论,我认为更好的是"收集(df1,Hand,Present,Present_R:Present_L)%>%arrange(id)%>%mutate(id = row_number() ,Hand = str_remove(Hand,".*_"),Dominant = Dominant == Hand)` (2认同)