如何使用R从经纬度数据生成物种存在/缺乏矩阵

时间:2019-10-11 14:57:47

标签: r

我有一长串经纬度数据的物种。

Sample Data

我想使用经/纬度数据为所有物种生成不存在矩阵(1,0)。但是,在同一纬度/经度(位置)中可能会出现多个物种。如何在R中考虑这一点并在下面生成示例数据框。

Desired matrix

2 个答案:

答案 0 :(得分:0)

为位置创建一个新变量,并串联纬度:

table <- table%>%mutate(location = paste(long,lat,sep="/"))

然后张开桌子

table <- table%>%spread(Sp,location)

然后将其设置为假

table[,3:4] <- ifelse(is.na(table[,3:4]),0,1)

请确保根据要拥有的列数更改数字3:4

答案 1 :(得分:0)

使用 tidyverse 很容易。首先是一些示例数据:

library(tidyverse)

df <- tibble(
  Sp = c('SP1', 'SP1', 'SP2', 'SP2', 'SP2'),
  Long = c(118, 119, 118, 119, 119),
  Lat = c(10, 11, 10, 11, 12)
)

  Sp     Long   Lat
  <chr> <dbl> <dbl>
1 SP1     118    10
2 SP1     119    11
3 SP2     118    10
4 SP2     119    11
5 SP2     119    12

然后执行枢轴操作。 spread tidyr 中已被pivot_wider取代(尽管目前仍支持spread)。

df2 <- df %>% 
  mutate(present = 1) %>% # create a dummy column
  pivot_wider(names_from = Sp, values_from = present) %>% # turn 'Sp' column into 'SP1' and 'SP2'
  mutate_at(vars(SP1, SP2), ~ifelse(is.na(.), 0, 1)) # fill in missing columns with 0

   Long   Lat   SP1   SP2
  <dbl> <dbl> <dbl> <dbl>
1   118    10     1     1
2   119    11     1     1
3   119    12     0     1