如何在运行时更改R脚本中的列名?

时间:2014-12-03 00:38:47

标签: r

我有一个32列的表,以1到32的名字命名。例如:X1,X2 ...... X32

我想做一个ks-test比较一列到彼此。我已经创建了一个脚本,我想知道是否可以在运行时访问这些变量,动态更改它的引用:

i <- 1
j <- 1
while(i <= 32)  
{
   while(j<=32)
    {
       #how can I change next statement to sth like "table$X[i],table$X[j]"?
       x <- ks.test(table$X1,table$X2)
       #anyway, how to access D and p-value properties from x?      
       cat("x: ",x.SOMETHING,"\n");     
       j <- j + 1
    }  
    i <- i + 1
}

感谢。

2 个答案:

答案 0 :(得分:1)

我认为你可以使用paste()在运行时设置列名。

试试这个:

x <- ks.test(table[,paste('X',i, sep='')], table[,paste('X',j, sep='')])

另一个(小)的事情:我认为你可以使用while循环保存一些输入,而不是使用for循环:

for(i in 1:32){
  for(j in (i+1):32){ # There's no need to perform the same tests again and again
    # Your code goes here, 
    # and you don't have to increment the value of i and j
  }
}

答案 1 :(得分:0)

一般来说,您可以使用[[ ]]而不是$以编程方式访问列的名称(或列表中的条目),例如:

> x <- data.frame(a = 1:10, b = 10:1)
> sapply(colnames(x), function(current_colname) x[[current_colname]])

假设您的表名为x,(使用table作为变量名称是一个坏主意......它已经是基本函数的名称):

> x <- data.frame(a = runif(100), b = runif(100), c = runif(100))
> y <- expand.grid(col1 = colnames(x), col2 = colnames(x), stringsAsFactors = FALSE)
> y$p.value <- mapply(function(col1, col2) {
                        foo <- ks.test(x[[col1]], x[[col2]])
                        foo$p.value }, ## foo[["p.value"]] would also work here :-)
                      col1 = y$col1, col2 = y$col2)
> y
  col1 col2   p.value
1    a    a 1.0000000
2    b    a 0.6993742
3    c    a 0.8127483
4    a    b 0.6993742
5    b    b 1.0000000
6    c    b 0.9937649
7    a    c 0.8127483
8    b    c 0.9937649
9    c    c 1.0000000

使用plyr的{​​{1}}功能可以让您更轻松,我建议您查看它们。

另请注意,如果您不想对每对进行两次测试,则可以将m_ply(在测试之前)进行分组,如下所示:

y