R: How can I use apply on rows of a data.frame and get out $column_name?

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2010-03-23T02:08:14Z Indexed on 2010/03/23 2:11 UTC
Read the original article Hit count: 267

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about r

    Related posts about data.frame