0

I ask help for solving a big issue I'm having lately. I get a data frame like

df <- data.frame(x=c("c1","c2","c3"),A=c(0,1,-1),B=c(2,0,1),C=c(0,-1,-1))

and a file "tmp.csv" with the following conditions

A>0
B>1
C<0

I need to load these conditions, parse them and apply them on the data frame. so, for A I expect c1 and c2. for B, c1 and for C, c2, c3.

I've been trying to find something similar here but I didn't. maybe here there's a similar problem but I didn't get the solution. I also found the function

parse

that it might do the parsing but even reading the documentation I didn't get what it does...

I really don't know from to start (parse and make understand the conditions on the prompt). any help?

edit: I add here another request very close to the present one. if I need to check which "cx" satisfies all the conditions (here only A and B, let's discard C) and not taken one per time, what should I do?

I thought of using simply

lines <- readLines("tmp.csv")
expr <- lapply(lines, function(t) parse(text=t)[[1]])
do.call("subset", list(quote(df), expr))

but I get the error "'subset' must be logic".

Community
  • 1
  • 1
Stefano
  • 361
  • 1
  • 4
  • 21

1 Answers1

0

Let's assume you've used readLines to read in the file of conditions. Here I read from a textConnection rather than writing a file

tt<-textConnection("A>0
B>1
C<0")
lines <- readLines(tt)
# lines <- readLines("tmp.csv") in your case

Now we can parse these expressions into a list with lapply and parse()

expr <- lapply(lines, function(t) parse(text=t)[[1]])

Now we can apply each of these to the data.frame with lapply, do.call and subset

df <- data.frame(x=c("c1","c2","c3"),A=c(0,1,-1),B=c(2,0,1),C=c(0,-1,-1))
lapply(expr, function(x) do.call("subset", list(quote(df), x)))

# [[1]]
#    x A B  C
# 2 c2 1 0 -1
# 
# [[2]]
#    x A B C
# 1 c1 0 2 0
# 
# [[3]]
#    x  A B  C
# 2 c2  1 0 -1
# 3 c3 -1 1 -1
MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • Exactly what I was looking for!!! and definitely out of my knowledge. I'd've never got it... :) – Stefano Dec 10 '15 at 08:40