[英]Convert wide to long in two variables
I have a dataframe like this 我有这样的数据帧
df= data.frame(a1 = c(1,2,3), a2 = c(4,5,6), b1 = c(1,2,3), b2= c(4,NaN,6), id = c(1,2,3))
I want to get 我想得到
id a measure1 b measure2
1 1 a1 1 b1 1
2 2 a1 2 b1 2
3 3 a1 3 b1 3
4 1 a2 4 b2 4
5 2 a2 5 b2 NaN
6 3 a2 6 b2 6
I can make 我会做
df1 = df[, c(1,2,5)]
df2 = df[, c(3,4,5)]
library(reshape2)
df1_long = melt(df1,id.vars= 'id', measure.vars=c("a1", "a2"),
variable.name="a",
value.name="measure1")
df2_long = melt(df2,id.vars= 'id', measure.vars=c("b1", "b2"),
variable.name="b",
value.name="measure2")
df_new = cbind(df1_long, df2_long[, -1])
But I think there is an easier way 但我认为有一种更简单的方法
in base R, you could use the reshape
function. 在基数R中,您可以使用reshape
功能。 Then you can change the columns as you wish: 然后,您可以根据需要更改列:
transform(reshape(df,1:4,sep="",dir="long"),a_=paste0("a",time),b_=paste0("b",time))
id time a b a_ b_
1.1 1 1 1 1 a1 b1
2.1 2 1 2 2 a1 b1
3.1 3 1 3 3 a1 b1
1.2 1 2 4 4 a2 b2
2.2 2 2 5 NaN a2 b2
3.2 3 2 6 6 a2 b2
It's relative what you consider to be easier, but an option is to use dplyr
and tidyr
: 这是你认为更容易的相对,但一个选项是使用dplyr
和tidyr
:
df %>%
select(id, starts_with("a")) %>%
gather(a, measurement1, -id) %>%
bind_cols(df %>%
select(starts_with("b")) %>%
gather(b, measurement2))
id a measurement1 b measurement2
1 1 a1 1 b1 1
2 2 a1 2 b1 2
3 3 a1 3 b1 3
4 1 a2 4 b2 4
5 2 a2 5 b2 NaN
6 3 a2 6 b2 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.