2017-08-09 141 views
0

我試圖做一個逗號分隔字符串列的數據幀,看起來像這樣的二元轉化:逗號的二進制編碼分開字符串列

df <- data.frame(id = c(1,2,3), 
       mystring = c("test1,test2", "test2,test3", "test1")) 

print(df) 

    id mystring 
1 1 test1,test2 
2 2 test2,test3 
3 3  test1 

我想實現像二進制轉換:

df_result <- data.frame(id = c(1,2,3), 
         test1 = c(1,0,1), 
         test2 = c(1,1,0), 
         test3 = c(0,1,0)) 

print(df_result) 

    id test1 test2 test3 
1 1  1  1  0 
2 2  0  1  1 
3 3  1  0  0 
+0

第一步:拆分字符串。 – Roland

+1

試試'cbind(df [1],mtabulate(strsplit(as.character(df $ mystring),「,」)))' – akrun

+0

很棒..這就是我正在尋找的..謝謝@akrun – Codutie

回答

0

我們可以使用mtabulate

library(qdapTools) 
cbind(df[1], mtabulate(strsplit(as.character(df$mystring), ",")))