R拆分列中的分隔符并插入为新列(以二进制形式)

时间:2017-07-31 04:18:03

标签: r dataframe reshape strsplit

我的数据框如下

+---+-----------+
|lot|Combination|
+---+-----------+
|A01|A,B,C,D,E,F|
|A01|A,B,C      |
|A02|B,C,D,E    |
|A03|A,B,D,F    |
|A04|A,C,D,E,F  |
+---+-----------+

每个字母表都是一个用逗号分隔的字符,我想分开'组合'在每个逗号上,以二进制形式将拆分字符串作为新列插入。例如,所需的输出将是:

+---+-+-+-+-+-+-+
|lot|A|B|C|D|E|F|  
+---+-+-+-+-+-+-+
|A01|1|1|1|1|1|1|
|A01|1|1|1|0|0|0|
|A02|0|1|1|1|1|0|
|A03|1|1|0|1|0|1|
|A04|1|0|1|1|1|1|
+---+-+-+-+-+-+-+

任何帮助将不胜感激:)

3 个答案:

答案 0 :(得分:2)

使用dplyrtidyr的解决方案。 dt2是最终输出。

# Load packages
library(dplyr)
library(tidyr)

# Create example data frame
dt <- lot <- c("A01", "A01", "A02", "A03","A04")
Combination <- c("A,B,C,D,E,F", "A,B,C","B,C,D,E", "A,B,D,F", "A,C,D,E,F")
dt <- data_frame(lot, Combination)

# Process the data
dt2 <- dt %>%
  mutate(ID = 1:n()) %>%
  mutate(Combination = strsplit(Combination, split = ",")) %>%
  unnest() %>%
  mutate(Value = 1) %>%
  spread(Combination, Value, fill = 0) %>%
  select(-ID)

答案 1 :(得分:1)

请以可直接用作接听人员输入的表格提供您的样本输入数据。我自己在这里添加了相同的样本数据希望有所帮助。

library(tidyr)
library(dplyr)
lot <- c("A01", "A02", "A03","A04")
Combination <- c("A,B,C,D,E,F", "A,B,C","B,C,D,E", "A,C")
df <- data.frame(lot, Combination)
df

separate(df, Combination, into=paste("V",1:6, sep=""), sep=",") %>%
    gather(key, value,-lot) %>%
    filter(!is.na(value)) %>%
    mutate(yesno = 1) %>%
    distinct %>%
    spread(value, yesno, fill = 0) %>% select(-key)

要了解此处发生的事情,请分别从单独的()开始执行每一步。 %&gt;%是一个管道运算符,它是将前一行的结果添加为下一行的第一个参数的简写。

答案 2 :(得分:0)

另一种选择,使用方便的separate_rows()函数:

df <- read.table( text = "lot|Combination
A01|A,B,C,D,E,F
A01|A,B,C
A02|B,C,D,E
A03|A,B,D,F    
A04|A,C,D,E,F", sep ="|", header = TRUE) 

library(tidyverse)
df %>%
  mutate(id = row_number(), flg = 1) %>%
  separate_rows(Combination, sep = ",") %>%
  spread(Combination, flg)

给出:

  lot id  A  B  C  D  E  F
1 A01  1  1  1  1  1  1  1
2 A01  2  1  1  1 NA NA NA
3 A02  3 NA  1  1  1  1 NA
4 A03  4  1  1 NA  1 NA  1
5 A04  5  1 NA  1  1  1  1