Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.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_Conditional Statements_Sapply - Fatal编程技术网

R 基于多列和多行条件的嵌套条件语句

R 基于多列和多行条件的嵌套条件语句,r,conditional-statements,sapply,R,Conditional Statements,Sapply,我正试图创建一个物种共生矩阵。我有一个数据帧b.d species <- c("A","A","F","H","D","E","C","D") ID <- c("a1", "a2", "f1", "h1", "d1", "e1", "c1", "d2") loc <- c(1,2,2,1,3,5,2,3) time <- c("8:00","9:00","9:00","10:00","12:00","12:00","1:00","2:00") cn <- c(1:8

我正试图创建一个物种共生矩阵。我有一个数据帧b.d

species <- c("A","A","F","H","D","E","C","D")
ID <- c("a1", "a2", "f1", "h1", "d1", "e1", "c1", "d2")
loc <- c(1,2,2,1,3,5,2,3)
time <- c("8:00","9:00","9:00","10:00","12:00","12:00","1:00","2:00")
cn <- c(1:8)
data.frame(species, ID, loc, time, cn)

species  ID  loc  time cn
1   A    a1   1   8:00  1
2   A    a2   2   9:00  2
3   F    f1   2   9:00  3
4   B    b1   1  10:00  4
5   D    d1   3  12:00  5
6   E    e1   5  12:00  6
7   C    c1   2   1:00  7
8   D    d2   3   2:00  8
上面的代码适用于位置和时间标准,但物种[x]标准不知怎么搞砸了。仅应用第一个参数(物种[x]=“A”),其余结果为零。我认为sappy函数是一行一行地读取物种[x],这样物种[x]一次只能代表一个物种,我如何绕过这一点,以便每一行都与多个其他行进行检查?那么物种[x]可以代表物种的组合


谢谢。

嗨,帕特丽夏,你能澄清一下为什么你认为输出需要是
cn x cn
矩阵吗?根据您的标准,一个物种只能与
a
B
C
物种共存。因此,我们为什么还要考虑其他物种呢?请尝试再次解释你的逻辑。嗨,伊恩,谢谢你的回复。我希望输出在
cn x cn
矩阵中,因为我最终希望从共现矩阵创建一个df,其中包含每对物种共现的次数计数。我想输出不需要是一个矩阵——如果我能得到一个数据框,其中有两列表示物种对共存,那就更好了。那么,
A.a1
A.a2
A.a1
F.f1
,等等。这有意义吗?嗨,帕特里夏,你能澄清一下为什么你认为输出需要是
cn x cn
矩阵吗?根据您的标准,一个物种只能与
a
B
C
物种共存。因此,我们为什么还要考虑其他物种呢?请尝试再次解释你的逻辑。嗨,伊恩,谢谢你的回复。我希望输出在
cn x cn
矩阵中,因为我最终希望从共现矩阵创建一个df,其中包含每对物种共现的次数计数。我想输出不需要是一个矩阵——如果我能得到一个数据框,其中有两列表示物种对共存,那就更好了。那么,
A.a1
A.a2
A.a1
F.f1
,等等,这有意义吗?
instance <- as.data.frame(with(b.d, sapply(cn, function(x)
    ifelse(abs(loc- loc[x]) <=1 & abs(difftime(time, time[x], units = "mins")) <= 60 &
        ((b.d$species[x]=="A" & b.d$species[x]=="A")
        | (b.d$species[x]=="A" & b.d$species[x]=="B")
               | b.d$species[x]=="C"), 
           paste(b.d$species,b.d$ID,sep="."),0)))) 
    V1    V2    V3    V4   V5    V6    V7   V8
1  A.a1  A.a1  A.a1   0     0     0    0     0
2  A.a2  A.a2  A.a2  A.a2   0     0    0     0
3  F.f1  F.f1  F.f1  F.f1   0     0    0     0
4  0     B.b1  B.b1  B.b1   0     0    0     0
5  0      0     0     0     0     0    0     0
6  0      0     0     0     0   E.e1  E.e1  E.e1
7  0      0     0     0     0   C.c1  C.c1  C.c1
8  0      0     0     0     0   D.d2  D.d2  D.d2