R: How can I use apply on rows of a data.frame and get out $column_name?
- by John
I'm trying to access $a using the following example:
df<-data.frame(a=c("x","x","y","y"),b=c(1,2,3,4))
> df
a b
1 x 1
2 x 2
3 y 3
4 y 4
test_fun <- function (data.frame_in) {
print (data.frame_in[1])
}
I can now access $a if I use an index for the first column:
apply(df, 1, test_fun)
a
"x"
a
"x"
a
"y"
a
"y"
[1] "x" "x" "y" "y"
But I cannot access column $a with the $ notation: error: "$ operator is invalid for atomic vectors"
test_fun_2 <- function (data.frame_in) {
print (data.frame_in$a)
}
>apply(df, 1, test_fun_2)
Error in data.frame_in$a : $ operator is invalid for atomic vectors
Is this not possible?