Is there an "apply" type method that allows us to iterate through a data.frame
and process the rows in exactly the same way as if we were looping? When I do apply(df, 1, function(row){...})
the row
passed to the function function is NOT an actual data.frame
row.
df = data.frame(A=rnorm(3), B=letters[1:3])
for (i in 1:3)
{
row = df[i,]
print(row)
print(class(row))
print(typeof(row))
print(row$A)
print(row$B)
}
apply(df, 1, function(row)
{
print(row)
print(class(row))
print(typeof(row))
print(row$A)
print(row$B)
})
> df = data.frame(A=rnorm(3), B=letters[1:3])
>
> for (i in 1:3)
+ {
+ row = df[i,]
+ print(row)
+ print(class(row))
+ print(typeof(row))
+ print(row$A)
+ print(row$B)
+ }
A B
1 0.4179416 a
[1] "data.frame"
[1] "list"
[1] 0.4179416
[1] a
Levels: a b c
A B
2 1.35868 b
[1] "data.frame"
[1] "list"
[1] 1.35868
[1] b
Levels: a b c
A B
3 -0.1027877 c
[1] "data.frame"
[1] "list"
[1] -0.1027877
[1] c
Levels: a b c
>
> apply(df, 1, function(row)
+ {
+ print(row)
+ print(class(row))
+ print(typeof(row))
+ print(row$A)
+ print(row$B)
+ })
A B
" 0.4179416" "a"
[1] "character"
[1] "character"
Show Traceback
Rerun with Debug
Error in row$A : $ operator is invalid for atomic vectors
Edit 1
A comment to this answer says that apply
turns the data.frame
into a matrix so you end up getting vectors. I guess that's the problem. Maybe time for a dedicated data.frame
iterator?
Edit 2
As @thelatemail pointed it this may really be a duplicate of For each row in an R dataframe.