当您在R中具有多个唯一ID时,是否有R代码可以从宽转换为长? [英] is there an R code for converting from wide to long when you have more than 1 unique id in R?

查看:69
本文介绍了当您在R中具有多个唯一ID时,是否有R代码可以从宽转换为长?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将以下数据从宽转换为长.

I have the following data that i want to convert from wide to long.

id_1<-c(1,2,2,2)
s02.0<-c(1,1,4,7)
s02.1<-c(2,2,5,8)
s02.2<-c(NA,3,6,NA)
id_2<-c(1,1,2,3)
df1<-data.frame(id_1,s02.0,s02.1,s02.2,id_2)

我希望基于两个唯一的ID获得以下输出,并添加新的变量n,该变量定义了's02'在每一行中的位置

I would wish to have the following output based on two unique ids, and added new variable say n, that defines the position of 's02' in each row

id_1<-c(1,1,1,2,2,2,2,2,2,2,2,2)
id_2<-c(1,1,1,1,1,1,2,2,2,3,3,3)
s02<-c(1,2,NA,1,2,3,4,5,6,7,8,NA)
n<-c(1,2,3,1,2,3,1,2,3,1,2,3)
df2<-data.frame(id_1,id_2,s02,n)

推荐答案

我们可以使用 pivot_longer

library(tidyr)
library(dplyr)
df1 %>% 
  pivot_longer(cols = starts_with('s02'), values_to = 's02') %>%    
  group_by(id_1, id_2) %>% 
  mutate(n = row_number())

这篇关于当您在R中具有多个唯一ID时,是否有R代码可以从宽转换为长?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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