我有一长串经纬度数据的物种。
答案 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