首页 > 解决方案 > 从 R 中的一个现有列中的特定元素创建新列

问题描述

我目前有一个数据集和一个具有特定(无序)值的列,我需要这些值来绘制它。每个变量都是代表特定类别的整数,例如 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

基本上我想从 anx 1 到有序的 nx 6,这样我就可以对 1、2、3 等的每次出现求和。我尝试使用转置,但我无法在其他问题中对其进行排序。

请帮忙!

标签: rtranspose

解决方案


也许是这样的?

# 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

推荐阅读