r - 从 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 等的每次出现求和。我尝试使用转置,但我无法在其他问题中对其进行排序。
请帮忙!
解决方案
也许是这样的?
# 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
推荐阅读
- database - 连接到数据库服务器而不暴露网络共享
- groovy - 未加载 Groovy 增强功能(日期、集合、数字等)
- ldap - 保险库登录后创建保险库令牌 - 方法 ldap
- sql - 查询以显示每个用户提交的最少 3 条记录的前 3 条记录?
- sql - 如何在 DB2 中查询不同的列值,而不是不同的行?
- java - 模拟结果集导致空指针异常
- sql - 合并来自 BigQuery 的加载数据
- php - 如何通过 phpMyAdmin 连接到 mysql docker 容器?
- typescript - 如何告诉 typescript 我的函数返回一个由特定类扩展的类?
- node.js - 在 Inno Setup 安装过程中编写 Node app .js 配置