拆分列和名称中的字符
我想分割字符。虽然我有一个很大的数据框要工作,但下面的小例子展示了需要做什么。
mydf <- data.frame (name = c("L1", "L2", "L3"),
M1 = c("AC", "AT", NA), M2 = c("CC", "--", "TC"), M3 = c("AT", "TT", "AG"))
我想将变量 M1 的字符拆分为 M3 (在真实数据集中,我有 > 6000 个变量)
name M1a M1b M2a M2b M3a M3b
L1 A C C C A T
L2 A T - - T T
L3 NA NA T C A G
我尝试了以下代码:
func<- function(x) {sapply( strsplit(x, ""),
match, table= c("A","C","T","G", "--", NA))}
odataframe <- data.frame(apply(mydf, 1, func) )
colnames(odataframe) <- paste(rep(names(mydf), each = 2), c("a", "b"), sep = "")
odataframe
I want to split characters. Although I have a large dataframe to work, the following small example to show what need to be done.
mydf <- data.frame (name = c("L1", "L2", "L3"),
M1 = c("AC", "AT", NA), M2 = c("CC", "--", "TC"), M3 = c("AT", "TT", "AG"))
I want to split the characters for variables M1 to M3 (in real dataset I have > 6000 variables)
name M1a M1b M2a M2b M3a M3b
L1 A C C C A T
L2 A T - - T T
L3 NA NA T C A G
I tried the following codes:
func<- function(x) {sapply( strsplit(x, ""),
match, table= c("A","C","T","G", "--", NA))}
odataframe <- data.frame(apply(mydf, 1, func) )
colnames(odataframe) <- paste(rep(names(mydf), each = 2), c("a", "b"), sep = "")
odataframe
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
干得好:
Here you go:
Andrie 的代码作为可复制函数
测试一下
请不要将此选为正确答案。安德烈的答案显然是第一个正确答案。这只是他的代码扩展到更多情况。感谢您的提问,也感谢安德烈提供的代码。
Andrie's code as a replicable function
Test it out
Please don't vote this as the correct answer. Andrie's answer is clearly the first correct answer. This is just an extension of his code to more situations. Thanks for the question and thanks for the code Andrie.