【发布时间】:2021-10-04 16:12:47
【问题描述】:
我正在尝试为两列(Proteins 和 Positions.within.proteins)调用 str_split 函数,然后将相应的值连接到一个名为 ID 的新列中。
df <- data.frame(Proteins = c("Q99755;A2A3N6", "O00329", "O00444",
"O14965", "O14976", "Q6A1A2;O15530", "O43318", "O43526", "O43930;P51817",
"O60331"), Positions.within.proteins = c("276;223", "708", "41",
"162", "175", "84;111", "63", "628", "78;78", "270"))
这是我的代码。
my.function <- function(x, y){
protein.names <- str_split(x, ";")[[1]]
position.names <- str_split(y, ";")[[1]]
ID <- list()
for (i in 1:length(protein.names)){
ID[i] <- paste(protein.names[i], position.names[i], sep ="_")
}
ID.2 <- unlist(ID)
return(ID.2)
}
当我在单行上调用该函数时,它在某种程度上起作用。
row1 <- my.function(df$Proteins[1], df$Positions.within.proteins[1])
"Q99755_276" "A2A3N6_223"
但我的问题是:
- 如何将此函数应用于整个数据框?
- 如何将
"Q99755_276" "A2A3N6_223"转换为我想要的"Q99755_276;A2A3N6_223"
我想使用apply 函数,但不确定apply 函数是否可以接受两个参数。
这里显示了它应该是什么样子。
df.final <- data.frame(Proteins = c("Q99755;A2A3N6", "O00329", "O00444",
"O14965", "O14976", "Q6A1A2;O15530", "O43318", "O43526", "O43930;P51817",
"O60331"), Positions.within.proteins = c("276;223", "708", "41",
"162", "175", "84;111", "63", "628", "78;78", "270"), ID = c("Q99755_276;A2A3N6_223",
"O00329_708", "O00444_41", "O14965_162", "O14976_175", "Q6A1A2_84;O15530_111",
"O43318_63", "O43526_628", "O43930_78;P51817_78", "O60331_270"
))
有谁知道如何实现这些?非常感谢您的帮助!
【问题讨论】:
-
您能否展示列出了 ID 的示例表以及数据如何?看起来你需要
joingroup_by和concatenate -
@JasonMathews 感谢您的回复!我更新了我的帖子。我展示了示例表的前 10 行。
-
图片没有帮助,请与
dput(head(data))分享可重现的数据样本。 -
@AnoushiravanR 很高兴知道这个功能
dput(head(data))。非常有帮助。我更新了我的帖子。 -
@GuedesBF 我提供了可编辑的代码。你能解释一下
\(x)在你的代码中做了什么吗?
标签: r string dataframe apply strsplit