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?
You could use adply
from the plyr package instead:
library(plyr)
adply(df, 1, function (data.frame_in) print(data.frame_in$a))
because data.frame.in
is not a data.frame:
apply(df, 1, function(v){print(class(v))})
but you can access the named elements with:
test_fun_2 <- function (data.frame_in) {
+ print (data.frame_in['a'])}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With