2013-04-23 63 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