簡體   English   中英

將不同的向量合並到一個 0/1 dataframe

[英]Merging diferent vectors into a 0/1 dataframe

我有三個包含名稱的向量:

one  <- c("a","b","d","f") 
two  <- c("b", "e")
three<- c("a", "b", "c", "f")

我想將它們加入 dataframe (或矩陣)中,其中行是名稱,列是向量,值是 1 或 0 是向量中存在的名稱。 有沒有辦法在 R 中做到這一點?

我的預期結果應該是 dataframe ,如下所示:

  one two three
a 1   0   1
b 1   1   1
c 0   0   1
d 1   0   0
e 0   1   0
f 1   0   1

創建一個向量列表,然后使用所示的sapply 不使用任何包。

L <- list(one = one, two = two, three = three)

rnames <- sort(unique(unlist(L)))
m <- +sapply(L, function(x) rnames %in% x)
rownames(m) <- rnames

m

給予:

  one two three
a   1   0     1
b   1   1     1
c   0   0     1
d   1   0     0
e   0   1     0
f   1   0     1

變化

上面的sapply行可以寫得更緊湊,如下所示:

m <- +sapply(L, `%in%`, x = rnames)

或者我們可以使用outer 這也設置了行名:

m <- + outer(setNames(rnames, rnames), L, Vectorize(`%in%`))

一種tidyverse方法可能是構建三個對象的列表,將它們放入一個unnest中,取消嵌套值並使用pivot_wider獲取寬格式的數據。

library(tidyverse)

lst(one, two, three) %>%
   enframe() %>%
   unnest(cols = "value") %>%
   mutate(n = 1) %>%
   #spread(name, n, fill = 0) %>% #in earlier version of tidyr
   pivot_wider(names_from = name, 
              values_from = n, 
              values_fill = list(n = 0)) %>%
   arrange(value)

#  value   one   two three
#  <chr> <dbl> <dbl> <dbl>
#1 a         1     0     1
#2 b         1     1     1
#3 c         0     0     1
#4 d         1     0     0
#5 e         0     1     0
#6 f         1     0     1

我們可以使用base Rtablestack

table(stack(mget(c('one', 'two', 'three'))))
#    ind
#values one two three
#     a   1   0     1
#     b   1   1     1
#     c   0   0     1
#     d   1   0     0
#     e   0   1     0
#     f   1   0     1

或者使用來自mtabulateqdapTools

library(qdapTools)
t(mtabulate(mget(c("one", "two", "three"))))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM