用R中的小滴值填充空矩阵

拉希姆·迪娜(Rahim Dina)

我生成了一个小标题,其格式如下:

  V1 n
1 "Sam,Chris" 30
2 "Sam,Peter" 81
3 "Jeff,James" 5
4 "David,Jones" 6
5 "Harry,Otto" 8

我也有一个很大的矩阵,其中每行和每列均以名称命名,并且每个名称出现一次。所以我需要分割V1的每一行,以使矩阵的索引为:

   [Sam]
[Chris]30

例如,因此我需要以某种方式用逗号分开,然后填充矩阵,我将如何处理?

阿克伦

我们可能需要使用 separate_rows

library(tidyverse)
df1 %>%      
  separate_rows(V1, sep=",") 

如果我们想将输出作为 matrix

df1 %>%
   separate(V1, into = c("V1", "V2"), sep=",") %>%
   spread(V2, n, fill = 0) %>%
   column_to_rownames("V1")
#    Chris James Jones Otto Peter
#David    0    0    6   0    0
#Harry    0    0    0    8    0
#Jeff     0     5   0   0  0
#@Sam      30    0    0   0   81

通过在行名和列名中包含名字和姓氏,可以将其转换为方矩阵

tmp <- df1 %>%
       separate(V1, into = c("V1", "V2"), sep=",") 
lvls <- sort(unique(unlist(tmp[1:2])))
tmp %>% 
  mutate_at(vars(V1, V2), factor, levels = lvls) %>%
  spread(V2, n, fill = 0, drop = FALSE)

数据

df1 <- structure(list(V1 = c("Sam,Chris", "Sam,Peter", "Jeff,James", 
"David,Jones", "Harry,Otto"), n = c(30L, 81L, 5L, 6L, 8L)), 
 class = "data.frame", row.names = c("1", 
"2", "3", "4", "5"))

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章