0

我有一个数据框,我想在其上执行以下操作:

1)根据ceratin列(包含数字数据)重新编排数据框。

2)在数据框中添加一列,根据我用来排序的列的顺序为每一行分配一个数字。

3)按行名重新排序数据框:我需要这个,因为我想使用不同的列多次应用步骤 1-2,并且我不希望在运行之间保留上一次运行的顺序。

我写了一个函数来做我想要的:

 globalQ<-function(df,x){
 df<-df[order(df[,x]),]
 leng<-length(which(is.na(df[,x])==FALSE))
 lengu<-as.integer((leng)/6)
 qvec<-c(rep(1,lengu),rep(2,lengu),rep(3,leng-5*lengu),rep(4,lengu),rep(5,lengu),   rep(6,lengu),rep(NA, times=nrow(df)-leng))
 df$name<-qvec
 df
 }

这适用于一次一列,例如:df<-globalQ(exProbes,14)。

但我想使用几个不同的列来执行此操作,一次调用一列上的函数。

我想我需要的是 apply() 的某个版本,但我不知道如何使用数据框和单个列的函数来调用 apply()。

顺便说一句,我知道在多列上调用此函数将在它将创建的新列上创建一个名称冗余。我稍后会处理。

提前致谢

4

2 回答 2

0

每次调用函数时都不需要对数据框进行排序。您可以按这样的顺序将结果返回cbind到原始数据框并稍后对其进行排序。像这样:

qvec<-function(y){
 leng<-sum(!is.na(y))
 lengu<-as.integer((leng)/6)
 qvec<-c(rep(1:2,each=lengu),rep(3,leng-5*lengu),rep(4:6,each=lengu),rep(NA,length(y)-leng))
 qvec[order(order(y))]
}

with(mtcars, cbind(mtcars, name1=qvec(cyl), name2=qvec(disp))[order(cyl, disp),])

要使用任意列索引向量 ( indices) 调用它,然后按行名排序,请使用以下内容:

result <- mtcars
for(i in indices) result <- cbind(result, qvec(mtcars[,i]))
result[order(rownames(mtcars)),]
于 2013-08-29T15:17:29.340 回答
0
## for example,1's,2's,4's column is what you need,exProbes is your matrix
indices<-c(1,2,4)
x<-globalQ(exProbes,indices[1])
if (length(indices)>1) {
    for (i in indices[-1]) {
        x<-data.frame(x,globalQ(exProbes,i)) 
    }
}
于 2013-08-29T16:52:45.927 回答