从R中一个现有列中的特定元素创建新列

时间:2018-05-14 02:40:37

标签: r transpose

我目前有一个数据集和一个列,它具有我需要的特定(无序)值以绘制它。每个变量都是一个表示特定类别的整数,例如1 = VC,2 = C,3 = M等。值来自(1,2,3,4,5,8,9)。

我目前有这样的事情:

    # A tibble: 571 x 1
    id
    <int>
     1     2
     2     3
     3     3
     4     1
   # ... with 561 more rows

但是我试图得到这样的东西:

    # A tibble: n x 6
    id
    <int>  
    1 1 2 3 4 5 8 9 <- With these being the new columns 
    2 1 2 3 4 5 8 9
    3 1 2 3 4 5 8 9
    4 1 2 3 4 5 8 9
    #... etc

基本上我想从一个n x 1到一个有序的n x 6,所以我可以对每次出现的1,2,3等进行求和。我尝试使用转置,但我不能在其他问题中对它进行排序。

请帮助!

1 个答案:

答案 0 :(得分:0)

也许是这样的?

# create a dataframe
d <- data.frame(A = c(1,1,2,1,1), B = c(2,2,10,1,2))

> d
  A  B
1 1  2
2 1  2
3 2 10
4 1  1
5 1  2


# we group the data by the columns A and B, and constructs a temporary extra 
# column, X which is the number of items in each group. Finally we use spread 
# to transform the data into the wanted format.

> d %>% dplyr::group_by(A,B) %>% 
    dplyr::summarise(X = n()) %>% 
    tidyr::spread(B,X, fill = 0)

# which return the data shown below, 

# A tibble: 2 x 4
# Groups:   A [2]
  A   `1`   `2`  `10`
* <dbl> <dbl> <dbl> <dbl>
1     1     1     3     0
2     2     0     0     1