为了促进我的分析,我有一个很难达到的目标;据我所知,没有类似的问题。我在 Excel 中有一个很长的数据框,我在这里以更简单的形式在 R 环境中重现它:
A1 <- cbind("sp1","sp2","sp3", "sp4", "sp7", "sp8")
A2 <- cbind("sp1","sp3", "sp4", "sp7", "sp9")
A3 <- cbind("sp5","sp6","sp7", "sp10")
A4 <- cbind("sp1","sp2","sp7", "sp9", "sp10")
A5 <- cbind("sp3","sp4")
max_row <- 6
A1 <- c(A1, rep(NA, max_row - length(A1)))
A2 <- c(A2, rep(NA, max_row - length(A2)))
A3 <- c(A3, rep(NA, max_row - length(A3)))
A4 <- c(A4, rep(NA, max_row - length(A4)))
A5 <- c(A5, rep(NA, max_row - length(A5)))
df <-cbind(A1,A2, A3, A4, A5)
df <- as.data.frame(df)
df <- data.frame(lapply(df, as.character), stringsAsFactors=FALSE)
为了更好地理解我工作的环境,“sp”是物种,A* 是我检测到给定物种的位点。
我想将此数据帧转换为另一个结构如下的数据帧:
第一列包含地点名称,后面的都是物种名称(显然,只重复一次)。然后,我需要在给定站点中为存在分配“1”,为缺席分配“0”。
我花了很多时间来尝试实现我的目标,但对于我的 R 语法能力来说,这个问题太复杂了。
有人可以帮助我吗?
最佳答案
您可以以长格式收集数据来处理并添加显示站点上物种存在的列。然后使用 reshape2::dcast
以宽格式传播数据:
library(tidyverse)
library(reshape2)
df %>% gather(Site, Species) %>%
filter(!is.na(Species)) %>%
mutate(value = 1) %>% #Species are present on a site
dcast(Site~Species, value.var = "value", fill = 0)
# Site sp1 sp10 sp2 sp3 sp4 sp5 sp6 sp7 sp8 sp9
# 1 A1 1 0 1 1 1 0 0 1 1 0
# 2 A2 1 0 0 1 1 0 0 1 0 1
# 3 A3 0 1 0 0 0 1 1 1 0 0
# 4 A4 1 1 1 0 0 0 0 1 0 1
# 5 A5 0 0 0 1 1 0 0 0 0 0
关于r - 操作数据框(使用 R),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50573180/