2013-04-23 62 views
0

我無法迭代data.Frame。R通過數據幀進行迭代的結果是什麼?

# a is a dataframe, with names 'f','d','sess', ... 
for (x in a) 
# find all events BEFORE the event x 
# ('d' is the beginning of the event in ms, 'e' is the end of it) 
a[a$f < as.numeric(x['d']),] -> all_before 

x['Epe'] = min(as.numeric(x['d'])-all_before$f) 
} 

它只是不會改變我原來的data.frame。有沒有辦法改變我的一個數據幀在運行中,或者我應該絕對創建一個新的並填寫它? 謝謝!

+0

能詳細說明一下你想要什麼嗎?通常不需要明確的'for'循環。 – 2013-04-23 19:21:09

+1

而且請提供示例數據,這段代碼相當神祕。 – 2013-04-23 19:22:14

回答

0

數據幀本質上是一個列表。使用數據框作爲for循環的輸入與使用列表作爲輸入時的作用相同。

> for(x in list(x = 1:3, y = letters, z = lm(mpg ~ hp, data = mtcars))){print(x)} 
[1] 1 2 3 
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s" 
[20] "t" "u" "v" "w" "x" "y" "z" 

Call: 
lm(formula = mpg ~ hp, data = mtcars) 

Coefficients: 
(Intercept)   hp 
    30.09886  -0.06823 

它遍歷列表中的每個元素。在數據框的情況下,它意味着它遍歷數據框的列。

> dat <- data.frame(x = 1:3, y = rep("this is y", 3)) 
> dat 
    x   y 
1 1 this is y 
2 2 this is y 
3 3 this is y 
> for(i in dat){print(i)} 
[1] 1 2 3 
[1] this is y this is y this is y 
Levels: this is y 
+0

謝謝......我發現很難理解R語言中所有不同種類的數據容器之間的區別。我缺乏有關R的基本機制的知識。實際上,我想遍歷我的數據框(逐行... for(in)在這種情況下不起作用),訪問行數據並填充蒼蠅的新專欄。 – 2013-04-23 19:38:55

+1

@Loic你可以用for循環來做,但你應該使用'apply'語句來做這樣的事情。例如 - 這會在mtcars數據框中創建一個名爲「max」的新列,並將該行的最大值放入該列中:mtcars $ max < - apply(mtcars,1,max)' – Dason 2013-04-23 19:44:29

+0

它的工作完美。謝謝! – 2013-04-23 19:58:48