-1

I am currently using Python and R together (using rmagic/rpy2) to help select different user input variables for a certain type of analysis.

I have read a csv file and created a dataframe in R. What I have also done is allowed the users to input a number of variables of which the names must match those in the header (using Python).

For example if I create a data frame as such

%R data1 <- read.csv(filename, header =T)

I then have a number of user input variables that are currently strings in pythons that would look like this.

var_1 = 'data1$age'
var_2 = 'data1$sex'

How can I then use this string as runable code in R to reach into the correct column of the data frame as such:

%R variable1 <- data1$sex

Currently I have tried the assign function and others (I understand this might be far from the mark) but I always just get it coming out as such:

%R -i var_1  assign('variable1', var_1)   
%R print(variable1)

"data1$age"

I understand that I could assign values etc in R but I'm questioning if it is possible to turn a string into a runnable bit of code that could reach into a data.frame.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
tbaker
  • 9
  • 1
  • [Hadley's chapter on non-standard evaluation](http://adv-r.had.co.nz/Computing-on-the-language.html) is overkill for the problem at hand, but useful to understand what's happening. – alistaire Jan 28 '16 at 00:50

2 Answers2

1

Consider having Python call the R script as child process via command line passing the string variables as arguments. In R, use the double bracket column reference to use strings:

Python Script (using subprocess module)

import subprocess

var_1 = 'age' 
var_2 = 'sex'
Rfilename = '/path/to/SomeScript.R'

# BELOW ASSUMES RScript IS A SYSTEM PATH VARIABLE
p = subprocess.Popen(['RScript', Rfilename, var1, var2])

R Script

args <-commandArgs(trailingOnly=T)
var_1 <- as.character(args[1])
var_2 <- as.character(args[2])

data1 <- read.csv(filename, header =T)
variable1 <- data1[[var_1]]
variable2 <- data1[[var_2]]
Parfait
  • 104,375
  • 17
  • 94
  • 125
0

Yes it is possible:

var_1 <- "head(iris$Species)"
eval(parse(text=var_1))
# [1] setosa setosa setosa setosa setosa setosa
# Levels: setosa versicolor virginica
Pierre L
  • 28,203
  • 6
  • 47
  • 69
  • @tbaker please avoid "thankyouabsolutelyperfect" comment and accept the answer instead. –  Jan 28 '16 at 00:58
  • 1
    http://stackoverflow.com/questions/13649979/what-specifically-are-the-dangers-of-evalparse –  Jan 28 '16 at 00:58