Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在r中将出席/缺席表转换为长格式_R_Tidyverse - Fatal编程技术网

在r中将出席/缺席表转换为长格式

在r中将出席/缺席表转换为长格式,r,tidyverse,R,Tidyverse,我是个新手,我想我永远都是。 我试图对表格进行整理,结果显示该代码只是一个非常简短的示例: PlotA<-c(0,1,0,1,0,1,0,1,0,1) PlotB<-c(0,0,1,1,0,0,1,1,0,0) PlotC<-c(0,0,0,0,1,1,1,1,0,0) PlotD<-c(0,0,0,0,0,0,0,0,1,1) DF<-as.data.frame(cbind(PlotA,PlotB,PlotC,PlotD)) row.names(DF)<-

我是个新手,我想我永远都是。 我试图对表格进行整理,结果显示该代码只是一个非常简短的示例:

PlotA<-c(0,1,0,1,0,1,0,1,0,1)
PlotB<-c(0,0,1,1,0,0,1,1,0,0)
PlotC<-c(0,0,0,0,1,1,1,1,0,0)
PlotD<-c(0,0,0,0,0,0,0,0,1,1)

DF<-as.data.frame(cbind(PlotA,PlotB,PlotC,PlotD))
row.names(DF)<-paste0("Species",LETTERS[seq( from = 1, to = 10 )])
对于这个例子,四个图中只有两个图:

SpeciesRepeat<-c("SpecisB","SpecisD","SpecisF","SpecisH","SpecisJ","SpecisC","SpecisD","SpecisG","SpecisH")
PlotRepeat<-c(rep("PlotA",length(PlotA [PlotA==1])), rep("PlotB",length(PlotB [PlotB==1])))
DesierdResDF<-cbind(SpeciesRepeat,PlotRepeat)
图中对一个物种的每一次观察都用一行obs表示。 tidyverse和基本R代码都将受到欢迎

谢谢, Idan

以下是一种使用tidyverse的方法。我们首先为rownames添加一个新列,以长格式获取数据,然后选择value=1的行


获取以下信息:pivot_中出现错误,cols=starts_with Plot:找不到函数pivot_longer@Idan您可能需要更新tidyr。安装软件包'tidyr'
library(tidyverse)
DF %>%
  rownames_to_column('SpeciesRepeat') %>%
  pivot_longer(cols = starts_with("Plot"), names_to = 'PlotRepeat') %>%
  filter(value == 1) %>%
  select(-value) 

# A tibble: 15 x 2
#   SpeciesRepeat PlotRepeat
#   <chr>         <chr>     
# 1 SpeciesB      PlotA     
# 2 SpeciesC      PlotB     
# 3 SpeciesD      PlotA     
# 4 SpeciesD      PlotB     
# 5 SpeciesE      PlotC     
# 6 SpeciesF      PlotA     
# 7 SpeciesF      PlotC     
# 8 SpeciesG      PlotB     
# 9 SpeciesG      PlotC     
#10 SpeciesH      PlotA     
#11 SpeciesH      PlotB     
#12 SpeciesH      PlotC     
#13 SpeciesI      PlotD     
#14 SpeciesJ      PlotA     
#15 SpeciesJ      PlotD