Sam*_*bus 6 r pattern-matching dataframe
我有一个数据框,其前5行看起来如下:
Sample CCT6 GAT1 IMD3 PDR3 RIM15
001 0000000000 111111111111111111111 010001000011 0N100111NNNN 01111111111NNNNNN
002 1111111111 111111111111111111000 000000000000 0N100111NNNN 00000000000000000
003 0NNNN00000 000000000000000000000 010001000011 000000000000 11111111111111111
004 000000NNN0 11100111111N111111111 010001000011 111111111111 01111111111000000
005 0111100000 111111111111111111111 111111111111 0N100111NNNN 00000000000000000
Run Code Online (Sandbox Code Playgroud)
完整的数据集有2000个样本.我正在尝试编写代码,这将允许我告诉我所有样本中5列中每列的数字串是否是同质的(即全部为1或0).理想情况下,我还希望能够在答案的情况下区分1和0 True.从我的例子来看,预期结果将是:
Sample CCT6 GAT1 IMD3 PDR3 RIM15
001 TRUE (0) TRUE (1) FALSE FALSE FALSE
002 TRUE (1) FALSE TRUE (0) FALSE TRUE (0)
003 FALSE TRUE (0) FALSE TRUE (0) TRUE (1)
004 FALSE FALSE FALSE TRUE (1) FALSE
005 FALSE TRUE (1) TRUE (1) FALSE TRUE (0)
Run Code Online (Sandbox Code Playgroud)
我没有坚持使用逻辑,我可以使用字符,只要它们可以用来区分不同的类.理想情况下,id喜欢在类似的数据框中返回结果.
我遇到了最基本的第一步,就是让R告诉字符串是否包含所有相同的值.香港专业教育学院尝试使用各种表达式grep,regexpr但无法得到一个结果,我可以使用ddply或类似的东西来应用整个数据框.以下是我为此步骤尝试过的一些示例:
a = as.character("111111111111")
b = as.character("000000000000")
c = as.character("000000011110")
> grep("1",a)
[1] 1
> grep("1",c)
[1] 1
> regexpr("1",a)
[1] 1
attr(,"match.length")
[1] 1
> regexpr("1",c)
[1] 8
attr(,"match.length")
[1] 1
Run Code Online (Sandbox Code Playgroud)
我非常感谢帮助我解决这个问题,或帮助我实现更大的目标.
这是一个REGEX表达式,它将匹配带有一个或多个字符的零或1:
(^[0]+$)|(^[1]+$)
Run Code Online (Sandbox Code Playgroud)
以下将匹配:0000 0 111111 11 1
这将不匹配:000001
这是一个完整的解决方案。可能有点矫枉过正,但也很有趣。
关键是markTRUE功能。它使用反向引用 ( \\1) 来引用先前与第一个带括号的子表达式匹配的子字符串( 或 )0。1
正则表达式表示“匹配以或"^(0|1)(\\1)+$"开头的任何字符串,然后(直到字符串结尾)重复 1 次或多次相同的字符 — 无论它是什么”。稍后在对 的同一调用中,我根据需要使用相同的反向引用来替换或。01gsub()"TRUE (0)""TRUE (1)"
首先读入数据:
dat <-
read.table(textConnection("
Sample CCT6 GAT1 IMD3 PDR3 RIM15
001 0000000000 111111111111111111111 010001000011 0N100111NNNN 01111111111NNNNNN
002 1111111111 111111111111111111000 000000000000 0N100111NNNN 00000000000000000
003 0NNNN00000 000000000000000000000 010001000011 000000000000 11111111111111111
004 000000NNN0 11100111111N111111111 010001000011 111111111111 01111111111000000
005 0111100000 111111111111111111111 111111111111 0N100111NNNN 00000000000000000"),
header=T)
Run Code Online (Sandbox Code Playgroud)
然后释放正则表达式:
markTRUE <- function(X) {
gsub(X, pattern = "^(0|1)(\\1)+$",
replacement = "TRUE (\\1)")
}
markFALSE <- function(X) {
X[!grepl("TRUE", X)] <- "FALSE"
return(X)
}
dat[-1] <- lapply(dat[-1], markTRUE)
dat[-1] <- lapply(dat[-1], markFALSE)
dat
# Sample CCT6 GAT1 IMD3 PDR3 RIM15
# 1 1 TRUE (0) TRUE (1) FALSE FALSE FALSE
# 2 2 TRUE (1) FALSE FALSE FALSE TRUE (0)
# 3 3 FALSE TRUE (0) FALSE TRUE (0) TRUE (1)
# 4 4 FALSE FALSE FALSE TRUE (1) FALSE
# 5 5 FALSE TRUE (1) TRUE (1) FALSE TRUE (0)
Run Code Online (Sandbox Code Playgroud)