拆分数据框的数字列

机器算法验证 r 数据集
2022-04-04 21:35:47

我有一个数据框 df ,如下所示

  name  position            
1 HLA   1:1-15            
2 HLA   1:2-16 
3 HLA   1:3-17         

我想根据“:”字符将位置列分成两列,这样我得到

name    seq    position            
1 HLA   1       1-15            
2 HLA   1       2-16 
3 HLA   1       3-17 

所以我认为这可以解决问题,

df <- transform(df,pos = as.character(position)) 

df_split<- strsplit(df$pos, split=":")

#found this hack from an old mailing list post
df <- transform(df, seq_name= sapply(df_split, "[[", 1),pos2= sapply(df_split, "[[", 2))

但是我收到一个错误

Error in strsplit(df$pos, split = ":") : non-character argument

有什么问题?你如何在 R 中实现这一点。我在这里简化了我的案例,实际上数据框运行到超过十万行。

3个回答
df_split<- strsplit(as.character(df$position), split=":")
df <- transform(df, seq_name= sapply(df_split, "[[", 1),pos2= sapply(df_split, "[[", 2))
> 
> df
  name position    pos seq_name pos2
1  HLA   1:1-15 1:1-15        1 1-15
2  HLA   1:2-16 1:2-16        1 2-16
3  HLA   1:3-17 1:3-17        1 3-17

这是使用 tidyr.separate() 的单行方法:

library(tidyr)
df <- separate(df, position, into = c("seq","position"), sep = ":", extra = "merge")

“诀窍”是使用do.call.

> a <- data.frame(x = c("1:1-15", "1:2-16", "1:3-17"))
> a
       x
1 1:1-15
2 1:2-16
3 1:3-17
> a$x <- as.character(a$x)
> a.split <- strsplit(a$x, split = ":")
> tmp <-do.call(rbind, a.split)
> data.frame(a, tmp)
       x X1   X2
1 1:1-15  1 1-15
2 1:2-16  1 2-16
3 1:3-17  1 3-17