0

I have the following two data frames (the real data frames are much larger). I would like to determine at which position(s) both data frames contain a 3 (in this example spot [2,1] only).

a<-c(1,3,5)
b<-c(2,3,4)
c<-c(3,3,4)
d<-c(2,4,7)
e<-cbind(a,b)
f<-cbind(c,d)
colnames(e)<-c("a","b")
colnames(f)<-c("a","b")

Results:

e
## a b
## 1 2
## 3 3
## 5 4

f

## a b
## 3 2
## 3 4
## 4 7

I've tried to use the following function, but it doesn't work.

fun<-function(x)
{ifelse(e$x==3 & f$x==3, "yes","no")}
Vs<-c("a","b")
lapply(Vs, fun)

Does anyone have any ideas, specifically on how use a variable as the character after the extraction operator ($) in a user written function?

Ben Bolker
  • 211,554
  • 25
  • 370
  • 453
  • use `[[` instead of `$` ... – Ben Bolker Aug 02 '14 at 21:31
  • 1
    How is this the most asked question in this tag and yet we still don't have a canonical duplicate? – MrFlick Aug 02 '14 at 21:32
  • @MrFlick This is the closest [tag:r-faq]: http://stackoverflow.com/questions/1169456/in-r-what-is-the-difference-between-the-and-notations-for-accessing-the – Thomas Aug 02 '14 at 21:35
  • Thanks @Thomas. I should add that to my favorites. Maybe even edit to include the $ in the title. – MrFlick Aug 02 '14 at 21:37
  • @Thomas: But neither the question nor the top answer addresses `$` at all... – krlmlr Aug 02 '14 at 21:38
  • 2
    maybe not canonical, but http://stackoverflow.com/questions/3079415/define-right-parameter-with-a-variable-in-r – Ben Bolker Aug 02 '14 at 21:44
  • @krlmlr True, not explicitly, but the accepted answer is just a copy-paste of the documentation, which (with a click and a little scrolling) gets you to the relevant information. – Thomas Aug 02 '14 at 21:52
  • I can't add an answer, so here's mine. Those aren't `data.frames`, they're matrices. Try this: `g <- (e == 3 & f == 3); c(row(g)[g], col(g)[g])` – Rich Scriven Aug 02 '14 at 22:04

1 Answers1

1

Here you go:

fun <- function(x) { ifelse(e[,x] == 3 & f[,x] == 3, "yes", "no") }
Vs <- c("a", "b")
lapply(Vs, fun)
janos
  • 120,954
  • 29
  • 226
  • 236