我坚持创建正确的正则表达式模式,该模式将拆分我的数据框列的内容,而不会让我失去任何元素。我必须使用包中的separate()函数,tidyr因为这是更长处理管道的一部分。由于我不想丢失字符串中的任何元素,因此我正在开发一个前瞻/后视表达式。
需要拆分的字符串可以遵循以下模式之一:
- 只有字母(例如'abcd')
- 字母破折号(例如'abcd-123')
- 字母数字(例如'abcd1234')
列内容应该被分成最多3 列,每组一列。
我想在每次元素更改时拆分,所以在字母之后和破折号之后。可以有一个或多个字母,一个或多个数字,但只能有一个破折号。只包含字母的字符串,不需要拆分。
这是我尝试过的:
library(tidyr)
myDat = data.frame(drugName = c("ab-1234", 'ab-1234', 'ab-1234',
'placebo', 'anotherdrug', 'andanother',
'xyz123', 'xyz123', 'placebo', 'another',
'omega-3', 'omega-3', 'another', 'placebo'))
drugColNames = paste0("X", 1:3)
# This pattern doesn't split strings that only consist of number and letters, e.g. "xyz123" is not split after the letters.
pat = '(?=-[0-9+])|(?<=[a-z+]-)'
# This pattern splits at all the right places, but the last group (the numbers), is separated and not kept together.
# pat = '(?=-[0-9+]|[0-9+])|(?<=[a-z+]-)'
splitDat = separate(myDat, drugName,
into = drugColNames,
sep = pat)
拆分的输出应该是:
"ab-1234" --> "ab" "-" "123"
"xyz123" --> "xyz" "123"
"omega-3" --> "omega" "-" "3"
非常感谢您在这方面提供帮助。:)