Heyho, 我想分割我的数据框,如下所示:
ID name1_attr1 name1_attr2 name2_attr2 ...
1 2 3 1
2 1 3 4
3 3 4 2
4 6 7 5
成:
ID name attr1 attr2
1 1 2 3
2 1 1 3
3 1 3 4
4 1 6 7
1 2 1
2 2 4
3 2 2
4 2 5
我真的不确定该怎么做?你有任何暗示或开始吗? 在此先感谢:)
答案 0 :(得分:3)
我们可以使用melt
中的data.table
,patterns
可以使用多个library(data.table)
melt(setDT(df),measure = patterns("attr1", "attr2"),
value.name = c("attr1", "attr2"), variable.name = "name")
# ID name attr1 attr2
#1: 1 1 2 3
#2: 2 1 1 3
#3: 3 1 3 4
#4: 4 1 6 7
#5: 1 2 NA 1
#6: 2 2 NA 4
#7: 3 2 NA 2
#8: 4 2 NA 5
df <- structure(list(ID = 1:4, name1_attr1 = c(2L, 1L, 3L, 6L), name1_attr2 = c(3L,
3L, 4L, 7L), name2_attr2 = c(1L, 4L, 2L, 5L)), .Names = c("ID",
"name1_attr1", "name1_attr2", "name2_attr2"), class = "data.frame", row.names = c(NA,
-4L))
$("#btn").on("click", dowork);
function dowork() {
document.getElementById("foo").innerHTML = "working";
setTimeout(function() {
var i, j, row = 5;
var html = "";
for (i = 1; i <= row; i++) {
for (j = 1; j <= i; j++) {
html += "<span>" + j + "</span>";
}
html += "</br>";
}
console.log(html);
document.getElementById("print_here").innerHTML = html;
}, 50);
}
答案 1 :(得分:2)
您可以尝试tidyverse
解决方案并使用gather
和spread
的组合。
d <- read.table(text="ID name1_attr1 name1_attr2 name2_attr2
1 2 3 1
2 1 3 4
3 3 4 2
4 6 7 5", header=T)
library(tidyverse)
d %>%
gather(k, v, -ID) %>%
separate(k, c("name","b"), sep = "_") %>%
spread(b, v, fill = "") %>%
arrange(name)
ID name attr1 attr2
1 1 name1 2 3
2 2 name1 1 3
3 3 name1 3 4
4 4 name1 6 7
5 1 name2 1
6 2 name2 4
7 3 name2 2
8 4 name2 5