在r中的数据框中提取每个字符串的第一部分

use*_*212 2 r

我有一个数据框M.我想提取每个字符串分隔的第一部分":".我使用strsplit但结果是一个大字符而不是数据框.有人可以帮忙吗?

M <- read.table(text=
"1/1:205,54,0:18:0:57 1/1:141,39,0:13:0:42   0/0:0,54,255:18:0:45 1/1:174,48,0:16:0:51 0/0:0,84,255:28:0:75 
 0/0:0,78,255:26:0:99 0/0:0,63,255:21:0:86   0/0:0,45,255:15:0:68 0/0:0,48,255:16:0:71 0/0:0,132,255:44:0:99
 0/0:0,78,255:26:0:89 0/0:0,78,255:26:0:89   0/0:0,36,255:12:0:47 0/0:0,33,255:11:0:44 0/0:0,108,255:36:0:99
 0/0:0,75,255:25:0:99 0/0:0,54,255:18:0:78   0/0:0,69,255:23:0:93 0/0:0,33,255:11:0:57 0/0:0,96,255:32:0:99 
 0/0:0,60,75:21:0:74  0/0:0,51,84:17:0:65    0/0:0,48,64:17:0:62  0/0:0,42,65:15:0:56  0/0:0,84,99:28:0:98 ",
head=F, stringsAsFactors=F)
S <- sapply(strsplit(M, ":"), "[", 1)
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

It may not be best to use strsplit as we are only interested in a substring. Assuming that the OP is interested in understanding how strsplit can be used for this example dataset, a modification of the OP's code would be to use a nested lapply/sapply loop.

 M[] <- lapply(M, function(x) sapply(strsplit(as.character(x), ':'),'[',1))
 M
 #   V1  V2  V3  V4  V5
 #1 1/1 1/1 0/0 1/1 0/0
 #2 0/0 0/0 0/0 0/0 0/0
 #3 0/0 0/0 0/0 0/0 0/0
 #4 0/0 0/0 0/0 0/0 0/0
 #5 0/0 0/0 0/0 0/0 0/0
Run Code Online (Sandbox Code Playgroud)

或者由于列都相似,我们可以unlist使用strsplit输出分配原始数据集,以便我们可以保持原始结构对于我们得到的输出完好无损.

  M[] <- sapply(strsplit(unlist(M), ':'),'[',1)
Run Code Online (Sandbox Code Playgroud)

或者更快的选项是使用stri_extract_firstfrom stringi来提取不是的字符:.

  library(stringi)
  M[] <- stri_extract_first(unlist(M), regex='[^:]+')
Run Code Online (Sandbox Code Playgroud)