>我有以下数据框:
dat <- data.frame(
c = c(1 , 2) , a1 = c(1 , 2) , a2 = c(3 , 4) , b1 = c(5 , 6) , b2 = c(7 , 8)
)
c a1 a2 b1 b2
1 1 1 3 5 7
2 2 2 4 6 8
我想根据共享前缀合并列以成为此数据框:
dat2 <- data.frame(
c = c(1 , 2 , 1 , 2) , a = c(1 , 2 , 3 , 4) , b = c(5 , 6 , 7 , 8)
)
c a b
1 1 1 5
2 2 2 6
3 1 3 7
4 2 4 8
我能想到的唯一方法是尝试使用 melt()
.这是我的尝试:
melt(dat , measure.vars = c(grep("^a" , colnames(dat)) , grep("^b" , colnames(dat))))
variable value
1 1 a1 1
2 2 a1 2
3 1 a2 3
4 2 a2 4
5 1 b1 5
6 2 b1 6
7 1 b2 7
8 2 b2 8
>
不用说,这是不正确的。
在这种情况下
,基本R的reshape
实际上非常适合。
reshape(dat, idvar="c", direction="long", sep="", varying=-1, timevar=NULL)
# c a b
#1.1 1 1 5
#2.1 2 2 6
#1.2 1 3 7
#2.2 2 4 8
sep=""
实质上告诉reshape()
组标识符(在本例中为 a
和 b
)和变量名中的time
指示符 - (在本例中为 1
和 2
)之间没有任何内容。因此,所有重命名都是自动处理的。
如果我也不设置timevar=NULL
,可能会更明显:
reshape(dat, idvar="c", direction="long", sep="", varying=-1)
# c time a b
#1.1 1 1 1 5
#2.1 2 1 2 6
#1.2 1 2 3 7
#2.2 2 2 4 8
如果有许多 id 变量希望为其他融化数据保持恒定,请尝试以下代码:
# an example bit of data
dat2 <- cbind(x=1:2,y=2:3,z=3:4, dat)
dat2
# x y z c a1 a2 b1 b2
#1 1 2 3 1 1 3 5 7
#2 2 3 4 2 2 4 6 8
idv <- match(c("x","y","z","c"), names(dat2))
reshape(dat2, idvar=idv, direction="long", sep="", varying=-idv, timevar=NULL)
# x y z c a b
#1.2.3.1.1 1 2 3 1 1 5
#2.3.4.2.1 2 3 4 2 2 6
#1.2.3.1.2 1 2 3 1 3 7
#2.3.4.2.2 2 3 4 2 4 8
library(tidyr)
library(dplyr)
dat %>%
gather(key, value, -c) %>% # this gets you were you were...
separate(key, into = c("letter", "number"), sep = 1) %>%
spread(letter, value) %>%
select(-number)
我们可以使用 data.table
中的melt
,这需要多个patterns
measure
library(data.table)
melt(setDT(dat), measure=patterns("^a\d+", "^b\d+"),
value.name=c("a", "b"))[, variable:= NULL][]
# c a b
#1: 1 1 5
#2: 2 2 6
#3: 1 3 7
#4: 2 4 8