需要以此来重塑data.frame
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<canvas id ="myCanvas"></canvas>
</body>
</html>
对此:
TestID Machine1Measure Machine1Count Machine2Measure Machine2Count
1 10006 11 14 16 24
2 10007 23 27 32 35
下面是创建每个代码的代码。看着R中的重塑,但不知道如何拆分名称
注意:这是列的子集-共有70-140台计算机。我该如何简化呢?
TestID Machine Measure Count
1 10006 1 11 14
2 10006 2 16 24
3 10007 1 23 27
4 10007 2 32 35
答案 0 :(得分:5)
以下内容再现了您的预期输出:
df %>%
gather(key, value, -TestID) %>%
separate(key, into = c("tmp", "what"), sep = "(?<=\\d)") %>%
separate(tmp, into = c("tmp", "Machine"), sep = "(?=\\d+)") %>%
spread(what, value) %>%
select(-tmp)
# TestID Machine Count Measure
#1 10006 1 14 11
#2 10006 2 24 16
#3 10007 1 27 23
#4 10007 2 35 32
说明:我们将数据从宽到长整形,并在再次从长到宽重塑之前,使用两个separate
调用来分隔各种值和id。 (我们使用积极的前瞻性和积极的后备态度将密钥分为必填字段。)
df <- read.table(text =
" TestID Machine1Measure Machine1Count Machine2Measure Machine2Count
1 10006 11 14 16 24
2 10007 23 27 32 35", header = T)
答案 1 :(得分:3)
<mat-grid-list [cols]="breakpoint" rowHeight="200px"
(window:resize)="onResize($event)">
<mat-grid-tile>1</mat-grid-tile>
<mat-grid-tile>2</mat-grid-tile>
<mat-grid-tile>3</mat-grid-tile>
</mat-grid-list>
可以在一data.table
内完成所有这些工作,这比MauritsEvers提供的(完全有效的)tidyverse解决方案快30倍。
它使用melt
定义名称中带有“ Measure”和“ Count”的列,然后将这些列融合为patterns
中的列名称
value.name
library( data.table )
melt( setDT( b),
id.vars = c("TestID"),
measure.vars = patterns( ".*Measure", ".*Count"),
variable.name = "Machine",
value.name = c("Measure", "Count") )
# TestID Machine Measure Count
# 1: 10006 1 11 14
# 2: 10007 1 23 27
# 3: 10006 2 16 24
# 4: 10007 2 32 35
答案 2 :(得分:3)
由于没有其他人喜欢reshape()
,因此我将添加一个答案:
reshape(
setNames(b, sub("^.+(\\d+)(.+)$", "\\2.\\1", names(b))),
idvar="TestID", direction="long", varying=-1, timevar="Machine"
)
# TestID Machine Measure Count
#10006.1 10006 1 11 14
#10007.1 10007 1 23 27
#10006.2 10006 2 16 24
#10007.2 10007 2 32 35
它永远不会与data.table
竞争纯速度,而是使用以下方法对200万行进行简短测试:
bbig <- b[rep(1:2,each=1e6),]
bbig$TestID <- make.unique(as.character(bbig$TestID))
#data.table - 0.06 secs
#reshape - 2.30 secs
#tidyverse - 56.60 secs