Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dataframe

r

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?

like image 656
John Avatar asked Mar 23 '10 02:03

John


2 Answers

You could use adply from the plyr package instead:

library(plyr)
adply(df, 1, function (data.frame_in) print(data.frame_in$a))
like image 101
hadley Avatar answered Oct 20 '22 03:10

hadley


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'])}
like image 11
xiechao Avatar answered Oct 20 '22 04:10

xiechao