R因子级别作为列名和计数值

时间:2018-09-20 13:26:22

标签: r

我希望将不同变量的因子水平作为列名,并将每个PatID的计数值作为值。 我有这个:

PatID I250 M206 X560
  1     2    1   0
  2     2    1   1
  3     1    2   2

我想要的是以下内容:

Metadata file '.dll' could not be found

有人可以帮忙吗?我尝试了dcast和其他方法,但结果从未出现

1 个答案:

答案 0 :(得分:1)

data_sample <- data.frame(
  PatID   = c(1L, 1L, 1L, 2L, 2L, 3L, 3L, 3L, 3L),
  status1 = c("I250", "NA", "NA", "X560", "M206", "NA", "NA", "M206", "NA"),
  status2 = c(".", "M206", "NA", "I250", "I250", "M206", "NA", "NA", "X560"),
  status3 = c(".", "I250", "NA", "NA", "NA", "I250", "X560", "NA", "NA")
)

library(tidyverse)
data_sample %>%
  gather(status_num, value, -PatID) %>%
  filter(value != "NA", value != ".") %>%
  count(PatID, value) %>%  # Improvement by @antoniosk 
  spread(value, n, fill = 0)

# A tibble: 3 x 4
# Groups:   PatID [3]
  PatID  I250  M206  X560
  <int> <int> <int> <int>
1     1     2     1    NA
2     2     2     1     1
3     3     1     2     2