首页 > 解决方案 > 在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个地点)

标签: rdataframe

解决方案


试试这种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))

推荐阅读