r - 在R中转换一个数据框,根据一个变量重新组织
问题描述
我有一个名为 data1 的这种类型的数据框:
individual location type
1 site1 1
2 site2 3
3 site3 2
4 site4 3
5 site5 1
6 site2 4
7 site5 2
我想将上面的数据转换为不同站点的行(观察),并计算每个站点的类型数,并获得以下信息:
location type1 type2 type3 type4
site1 1 0 0 0
site2 0 0 1 1
site3 0 1 0 0
site4 0 0 1 0
site5 2 1 0 0
如何创建具有上述格式的数据集?(以上简化,我的原始数据是2500个人和400个地点)
解决方案
试试这种tidyverse
接近你想要的方法。您可以将数据整形为长,获取数据框的值,然后整形为宽以获得预期结果。这里的代码:
library(tidyverse)
#Code
df %>%
#Mutate type
mutate(type=paste0('type',type)) %>%
#Mutate number of types
group_by(location,type) %>%
mutate(N=n()) %>% select(-individual) %>%
pivot_wider(names_from = type,values_from=N) %>%
replace(is.na(.),0) %>% select(sort(current_vars()))
输出:
# A tibble: 5 x 5
# Groups: location [5]
location type1 type2 type3 type4
<chr> <int> <int> <int> <int>
1 site1 1 0 0 0
2 site2 0 0 1 1
3 site3 0 1 0 0
4 site4 0 0 1 0
5 site5 1 1 0 0
使用的一些数据:
#Data
df <- structure(list(individual = 1:7, location = c("site1", "site2",
"site3", "site4", "site5", "site2", "site5"), type = c(1L, 3L,
2L, 3L, 1L, 4L, 2L)), class = "data.frame", row.names = c(NA,
-7L))
推荐阅读
- terraform - 在 azure 中运行的每个管道的负载均衡器后端池下获取额外的 VM
- typescript - 利用接口或类型来描述对象的键
- python - 由用户对 Dataframe 列执行计算并添加为新列
- php - 使用标志时 MySQL 连接被拒绝
- python - Apache SPark:groupby 未按预期工作
- amazon-web-services - 亚马逊个性化 SIMS 和个性化排名食谱是否支持元数据?
- html - 修复了具有全窗口拉伸和滚动时不重复的背景图像?
- r - R:如何在df中的5个变量中逐行找到10个最常见的对
- python - Python ModuleNotFound 等
- kotlin - 我应该为一个小列表使用 Android 分页库吗?