2014-12-03 50 views
0

我有一個32列的表格,從1到32之後以X命名。例如:X1,X2 ... X32如何在運行時更改R腳本中的列名?

我想做一個ks測試,將一列與所有其他列進行比較。我創建了一個腳本,我想知道是否有可能在運行時訪問這些變量,動態地改變它的參考:

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

您可以簡單地通過指數,例如訪問矩陣的列'x < - ks.test(table [,i],table [,j])''。無需使用任意分配的列名稱。 – voidHead 2014-12-03 00:43:13

+0

它似乎有效!有沒有關於訪問x.p-value和x.D屬性的正確方法的建議? – Alex 2014-12-03 01:00:34

+0

其他問題:字段索引是否爲零? – Alex 2014-12-03 01:01:27

回答

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 
    } 
} 
+0

謝謝,它的工作。但是這兩個論點都缺乏接近方形的布拉克。 – Alex 2014-12-03 01:25:07

+0

@亞歷克斯哎呀!抱歉,錯字...正確 – Barranka 2014-12-03 15:33:00

0

一般而言,您可以使用[[ ]]而非$以編程方式訪問列名稱(或列表中的條目),例如:

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

假設您的表名爲x,(使用table作爲變量名是一個糟糕的主意......它已經基函數的名稱):使用plyrm_ply

> 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 

功能使這更容易,我建議看看他們。

還要注意的是,如果你不想要測試每對兩次,你可以子集y(測試前),像這樣:

> y <- y[y[[1]] < y[[2]],] ## use <= if you want to keep the reflexive cases 
相關問題