R-如何创建T/F矩阵,取决于向量是否包含值



我正在尝试制作一个包含TRUE(1(和FALSE(0(的矩阵。目前我正在使用双for循环。

install.packages("phytools")
library(phytools)
A1 <- c("a", "b", "c")
A2 <- c("a", "e", "f")
A3 <- c("t", "o", "x")
c(A1, A2, A3)->Test
c("a", "b", "c", "e", "f", "t", "o", "x")-> list
capture.output(for( i in Test){
for( RT in list){
print(i %in%  RT)
x[Test, list] = i %in% RT
}
}, file = "/Users/Users/Desktop/Test")

虽然这在一定程度上起作用。它当前返回一个长度(test(x长度(list(的列表。我可以用将其强制转换为数据矩阵

matrix(unlist(read.table("/Users/Users/Desktop/Test")), 
ncol = 3, byrow = TRUE)-> Matrix

然而,我认为这并不能准确地测试"列表"的每个元素,例如A,是否在三个向量(A1、A2、A3(中的每一个中

我不确定哪里出了问题,也不知道如何直接将我的double-for-loop打印到矩阵中。

尝试这个

A1 <- c("a", "b", "c")
A2 <- c("a", "e", "f")
A3 <- c("t", "o", "x")
Test <- list(A1=A1,A2=A2,A3=A3)
c("a", "b", "c", "e", "f", "t", "o", "x")-> list

lapply(Test,function(x) list %in% x) -> tmp
final.df <- cbind(list, as.data.frame(tmp))
final.df
#>   list    A1    A2    A3
#> 1    a  TRUE  TRUE FALSE
#> 2    b  TRUE FALSE FALSE
#> 3    c  TRUE FALSE FALSE
#> 4    e FALSE  TRUE FALSE
#> 5    f FALSE  TRUE FALSE
#> 6    t FALSE FALSE  TRUE
#> 7    o FALSE FALSE  TRUE
#> 8    x FALSE FALSE  TRUE

创建于2018-07-26由reprex包(v0.2.0.9000(。

或用于环路

A1 <- c("a", "b", "c")
A2 <- c("a", "e", "f")
A3 <- c("t", "o", "x")
Test <- list(A1=A1,A2=A2,A3=A3)
c("a", "b", "c", "e", "f", "t", "o", "x")-> list
tmp2 <- list()

for (i in 1:length(Test)){
tmp2[[i]] <- list %in% Test[[i]]
}
names(tmp2) <- names(Test)
final.df <- cbind(list, as.data.frame(tmp2))
final.df
#>   list    A1    A2    A3
#> 1    a  TRUE  TRUE FALSE
#> 2    b  TRUE FALSE FALSE
#> 3    c  TRUE FALSE FALSE
#> 4    e FALSE  TRUE FALSE
#> 5    f FALSE  TRUE FALSE
#> 6    t FALSE FALSE  TRUE
#> 7    o FALSE FALSE  TRUE
#> 8    x FALSE FALSE  TRUE

创建于2018-07-26由reprex包(v0.2.0.9000(。

说明:lapply为三个列表运行function(x){list %in% x}并返回一个列表。

酷孩子们在R中使用apply而不是for loops。(你可以看到代码更短(

在我看来,OP具有list,它包含所有向量A1A2A3中的唯一元素。有兴趣知道哪个元素存在于哪个向量中。

一个选项是在long-format中转换数据,并使用tablereshape2::dcast函数汇总数据。

Test <- data.frame(A1, A2, A3, stringsAsFactors = FALSE)

选项1:使用table

library(tidyverse)
Test %>% gather(key, value) %>% 
table()
#      value
# key  a b c e f o t x
#   A1 1 1 1 0 0 0 0 0
#   A2 1 0 0 1 1 0 0 0
#   A3 0 0 0 0 0 1 1 1

选项2:使用reshape2::dcast

library(tidyverse)
library(reshape2)
Test %>% gather(key, value) %>%
dcast(value~key, fun.aggregate = function(x)length(x)>0 )
#   value    A1    A2    A3
# 1     a  TRUE  TRUE FALSE
# 2     b  TRUE FALSE FALSE
# 3     c  TRUE FALSE FALSE
# 4     e FALSE  TRUE FALSE
# 5     f FALSE  TRUE FALSE
# 6     o FALSE FALSE  TRUE
# 7     t FALSE FALSE  TRUE
# 8     x FALSE FALSE  TRUE

数据:

A1 <- c("a", "b", "c")
A2 <- c("a", "e", "f")
A3 <- c("t", "o", "x")

最新更新