假设我有一个这样的变量向量:
>variable
[1] "A1" "A1" "A1" "A1" "A2" "A2" "A2" "A2" "B1" "B1" "B1" "B1"
我想把它转换成这样的数据框:
treatment time
1 A 1
2 A 1
3 A 1
4 A 1
5 A 2
6 A 2
7 A 2
8 A 2
9 B 1
10 B 1
11 B 1
12 B 1
为此,我使用了 reshape2 的 colsplit 函数。它需要一个模式来分割字符串,但我很快意识到没有明显的模式来分割两个字符而没有任何空格。我尝试了“”并得到以下结果:
> colsplit(trialm$variable,"",names=c("treatment","time"))
treatment time
1 NA A1
2 NA A1
3 NA A1
4 NA A1
5 NA A2
6 NA A2
7 NA A2
8 NA A2
9 NA B1
10 NA B1
11 NA B1
12 NA B1
我还尝试了一个lookbehind或lookahead正则表达式:
>colsplit(trialm$variable,"(?<=\\w)",names=c("treatment","time"))
Error in gregexpr("(?<=\\w)", c("A1", "A1", "A1", "A1", "A2", "A2", "A2", :
invalid regular expression '(?<=\w)', reason 'Invalid regexp'
但它给了我上述错误。我怎么解决这个问题?