【问题标题】:constructing a function using colnames as variables使用 colnames 作为变量构造函数
【发布时间】:2015-12-14 08:13:26
【问题描述】:

我想在注释data.frame 的多个列下收集术语。 下面是 annot 的玩具数据集的第一行信息。

colnames(annot)
# [1] "HUGO.Name"   "Common.Name" "Gene.Class"  "Cell.Type"   "Annotation" 
annot[1,]
#   HUGO.Name Common.Name                           Gene.Class Cell.Type
# 1      CCL1        CCL1 Immune Response - Cell Type specific       aDC
#                                                            Annotation
# 1 Cell Type specific, Chemokines and receptors, Inflammatory response

到目前为止,我一直在迭代地编写 colnames,但我想学习如何编写一个函数来循环遍历 annot 的所有列(以及更普遍的其他 data.frames)。

这是我的手动方法:

yA <- unique(str_trim(unlist(strsplit(annot[, "Annotation"], ","))))
yC <- unique(str_trim(unlist(strsplit(annot[, "Cell.Type"], ","))))

yA
#  [1] "Cell Type specific"                  "Chemokines and receptors"           
#  [3] "Inflammatory response"               "Cytokines and receptors"            
#  [5] "Chronic inflammatory response"       "Th2 orientation"                    
#  [7] "T-cell proliferation"                "Defense response to virus"          
#  [9] "B-cell receptor signaling pathway"   "CD molecules"                       
# [11] "Regulation of immune response"       "Adaptive immune response"           
# [13] "Antigen processing and presentation"

如何构造函数“y”来简化此过程?我尝试了以下方法:

y <- function (i,n) {unique(str_trim(unlist(strsplit(i[, as.name(n)], ","))))}

但是,当我尝试使用此功能时出现错误。

yA <- y(annot, Annotation)
# Error in .subset(x, j) : invalid subscript type 'symbol'
# Called from: `[.data.frame`(i, , as.name(n))

我打算使用 yA 和 yC 的输出来制作如下列表:

# look up associated HUGO.Name per each term of yA
for (i in yA) {
eval(call("<-", as.name(i),
              annot[grepl(i, annot[,"Annotation"], fixed =T), "HUGO.Name"]))
}  
# make lists 
nSannot_list<- mget(yA)

【问题讨论】:

  • 我不确定我是否理解您在更新中的意图。你能以我的简化样本数据为例吗?
  • 谢谢!它完全实现了我的想法

标签: r function apply


【解决方案1】:

假设您从data.frame 开始:

mydf <- data.frame(
  v1 = c("A, B, B", "A, C,D"), 
  v2 = c("E, F", " G,H , E, I"), 
  v3 = c("J,K,L,M", "N, J, L, M, K"))

mydf
#        v1          v2            v3
# 1 A, B, B        E, F       J,K,L,M
# 2  A, C,D  G,H , E, I N, J, L, M, K

定义函数的一种方式如下所示。我坚持使用基本函数,但如果您愿意,可以使用“stringr”。

myFun <- function(instring) {
  if (!is.character(instring)) instring <- as.character(instring)
  unique(trimws(unlist(strsplit(instring, ",", fixed = TRUE))))
}

第一行只是检查输入是否是字符串。通常,在data.frames 中,默认情况下使用stringsAsFactors = TRUE 读入数据,因此您需要先执行该转换。第二行进行分割和修剪。为了提高效率,我在其中添加了fixed = TRUE

一旦有了这样的功能,您就可以使用apply(对于data.framematrix,按行或按列)或使用lapply(对于listdata.frame(将按列)。

## If `mydf` is a data.frame, and you want to go by columns
lapply(mydf, myFun) 
# $v1
# [1] "A" "B" "C" "D"
# 
# $v2
# [1] "E" "F" "G" "H" "I"
# 
# $v3
# [1] "J" "K" "L" "M" "N"

## `apply` can be used too. Second argument specifies whether by row or column
apply(mydf, 1, myFun)
apply(mydf, 2, myFun)

另一方面,如果您希望创建一个接受输入数据集名称和(裸、未引用)列的函数,则可以这样编写函数:

myOtherFun <- function(indf, col) {
  col <- deparse(substitute(col))
  unique(trimws(unlist(strsplit(as.character(indf[, col]), ",", TRUE))))
}

第一行将裸列名称捕获为字符串,以便可以在典型的my_data[, "col_wanted"] 形式中使用。

下面是使用的函数:

myOtherFun(mydf, v2)
# [1] "E" "F" "G" "H" "I"

【讨论】:

  • 谢谢!这很有启发性!我明白为什么我最初的尝试失败了。我仍在学习如何在 R 中编写函数和 for 循环
  • @seraphim711,没问题。希望它可以帮助您走上正确的道路;-)
猜你喜欢
  • 2012-01-07
  • 1970-01-01
  • 2014-12-29
  • 2019-02-22
  • 2015-04-17
  • 2023-03-24
  • 2021-10-10
  • 1970-01-01
  • 2013-06-20
相关资源
最近更新 更多