我想知道有没有一种方法可以宽格式我的long_data,以达到我的desired_output以下?

我试了pivot_wider(long_data, id_cols= -c(class, sub, order),names_from= DV, values_from= score)次,但没有成功.

library(tidyverse)
m="
class sub  order time DV score task_type
1     1    s-c   1    ac 1     simple
1     1    s-c   1    bc 2     simple
1     1    s-c   2    ac 3     complex
1     1    s-c   2    bc 4     complex
"

long_data = read.table(text = m, header = TRUE)
desired_output =
"
class sub  order DV_ac_T1 DV_ac_T2 DV_bc_T1 DV_bc_T2 task_type_T1  task_type_T2
1     1    s-c   1        3        2        4        simple        complex
"

推荐答案

我们可以使用pivot_widernames_glue来调整列名格式

library(tidyr)
pivot_wider(long_data, names_from = c(DV, time), 
     values_from = c(score, task_type), names_glue = "{.value}_{DV}_T{time}")

-输出

# A tibble: 1 × 11
  class   sub order score_ac_T1 score_bc_T1 score_ac_T2 score_bc_T2 task_type_ac_T1 task_type_bc_T1 task_type_ac_T2 task_type_bc_T2
  <int> <int> <chr>       <int>       <int>       <int>       <int> <chr>           <chr>           <chr>           <chr>          
1     1     1 s-c             1           2           3           4 simple          simple          complex         complex      

如果我们想要删除‘Score’

library(stringr)
pivot_wider(long_data, names_from = c(DV, time), 
     values_from = c(score, task_type), 
    names_glue = "{str_remove(str_c(.value, '_', DV), 'score_')}_T{time}")

-输出

# A tibble: 1 × 11
  class   sub order ac_T1 bc_T1 ac_T2 bc_T2 task_type_ac_T1 task_type_bc_T1 task_type_ac_T2 task_type_bc_T2
  <int> <int> <chr> <int> <int> <int> <int> <chr>           <chr>           <chr>           <chr>          
1     1     1 s-c       1     2     3     4 simple          simple          complex         complex        

R相关问答推荐

将复杂的组合列表转换为数据框架

R Tidymodels textercipes-使用spacyR进行标记化-如何从生成的标记列表中删除标点符号

如何写一个R函数来旋转最后n分钟?

如何通过Docker部署我的shiny 应用程序(多个文件)

将包含卷的底部25%的组拆分为2行

多个过滤器内的一个盒子在仪表板Quarto

Ggplot2中geom_tile的动态zoom

R中有约束的优化问题:如何用复数和对数效益函数解决问题?

KM估计的差异:SvyKm与带权重的调查

在不对R中的变量分组的情况下取两行的平均值

R中的Desolve:返回的导数数错误

Data.table::Shift type=允许扩展数据(&Q;LAG&Q;)

在鼠标悬停时使用Plotly更改geom_point大小

如何在R中的两列以上使用联合(&U)?

删除r中每个因素级别的最后2行

将矩阵中特定行的双精度值添加到下一行中

使用';IF';运算符判断数据框单元格中的给定值是否属于一组值

R-有没有办法比较列字符串之间的单个项目?

等价于Plot_ly R中的geom_函数

基于日期输入的子集数据集,其中应包括NAS作为 Select