2017-01-02 306 views
0

我正在R中使用for循環來創建新的向量。 '文件'包含多個或多於500行的多個數據幀。R在for循環中賦值變量

temp = list.files(pattern="*txt") 
files = lapply(temp, read.delim) 

pos = c(1:100) 
results = null 

for (i in pos) { 
    nameA = paste("A", i, sep = "_") 
    nameC = paste("C", i, sep = "_") 
    resA = assign(nameA, unlist(lapply(files, function(x) x$perA[x$position==i]))) 
    resC = assign(nameC, unlist(lapply(files, function(x) x$perC[x$position==i]))) 
    cbind(summary(resA), results) #incorrect 
    cbind(summary(resC), results) #incorrect 
} 

現在我想執行的薩& RESC「摘要」在「排名」的所有值。我想把這些結果放在1個數據幀(結果)中。我現在該怎麼做?

+0

所以基本上200列 - 名稱A和名稱C 100 pos 100到1右? –

+0

在'for'循環的每次迭代中使用'cbind()' –

+0

@ joel.wilson:回答你的第一個問題:的確如此。第二條評論:好的,但我不能只在for循環中執行sum = summary(nameA)。 – user1987607

回答

1

有點沿着這些線路:

# create a data.frame with 6 rows(since summary() returns a vector of 6 elements 
df <- data.frame(1:6) 
# set the rownames of df 
rownames(df) = names(summary(1:6)) 

for (i in pos) { 
    nameA = paste("A", i, sep = "_") 
    ... 
    xA = unlist(lapply(files, function(x) x$perA[x$position==i])) 
    xC = unlist(lapply(files, function(x) x$perC[x$position==i])) 
    df = cbind(df, as.numeric(summary(xA)), as.numeric(summary(xC))) 
    assign(nameA, xA) 
    assign(nameC, xC) 
} 

# set the column names of df 
df[1] = NULL # initial column removed 
colnames(df) = c("id", paste0("summary",c("A","C"), rep(1:100, each = 2))) 
+0

它回答你的問題嗎? –

0

是否有一個原因,以節省自己的,而不是一個列表內的每個向量?這將使進一步的分析更容易。

我們仍然可以將您的向量與mget組合成一個列表。然後將summary函數應用於此列表並使用cbind()將結果組合爲單個矩陣。

list_A <- mget(ls(pattern="A_[0-9]")) 
list_C <- mget(ls(pattern="C_[0-9]")) 
summary_A <- do.call(cbind,lapply(list_A,summary)) 
summary_C <- do.call(cbind,lapply(list_C,summary)) 
summary_All <- data.frame(summary_A, summary_C) 

當然你要小心是否有與環境中相同的命名模式的其他對象。