r creating an adjacency matrix from columns in a dataframe

我只是一个虾纸丫 提交于 2019-12-05 07:53:04

One way is to make the dataset into a "tidy" form, then use xtabs. First, some cleaning up:

df[] <- lapply(df, as.character)  # Convert factors to characters
df[df == "NA" | df == "" | is.na(df)] <- NA  # Make all blanks NAs

Now, tidy the dataset:

library(tidyr)
library(dplyr)
out <- do.call(rbind, sapply(grep("^Col_Cold", names(df), value = T), function(x){
  vars <- c(x, grep("^Col_Hot", names(df), value = T))
  setNames(gather_(select(df, one_of(vars)), 
    key_col = x,
    value_col = "value",
    gather_cols = vars[-1])[, c(1, 3)], c("cold", "hot"))
}, simplify = FALSE))

The idea is to "pair" each of the "cold" columns with each of the "hot" columns to make a long dataset. out looks like this:

out
#        cold        hot
# 1      pain  infection
# 2      Bump       <NA>
# 3      <NA>     Callus
# 4    muscle       <NA>
# 5      pain medication
# ...

Finally, use xtabs to make the desired output:

xtabs(~ cold + hot, na.omit(out))
#           hot
# cold       Callus flutter infection medication twitching walking
#   Bump          0       1         0          0         1       0
#   hemaloma      1       0         1          0         0       0
#   muscle        0       1         0          1         2       0
#   pain          1       0         2          2         1       1
#   sleep         0       0         1          1         0       1
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!