将列名称及其值拆分为行和列

时间:2018-01-10 10:03:28

标签: r dataframe

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

我真的不确定该怎么做?你有任何暗示或开始吗? 在此先感谢:)

2 个答案:

答案 0 :(得分:3)

我们可以使用melt中的data.tablepatterns可以使用多个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解决方案并使用gatherspread的组合。

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