能否在R Studio中与Python交互?能否混合使用R与Python?
Absolutely! You can totally interact with Python in RStudio and mix R and Python code seamlessly—this is a super popular workflow for anyone wanting to leverage the strengths of both languages. Let me break down how to do this using the reticulate package, which is the go-to tool for R-Python integration.
1. 第一步:安装并加载reticulate
This package acts as a bridge between R and Python, letting you call Python code, share variables, and even switch between interactive environments.
# Install the package if you haven't already install.packages("reticulate") # Load it into your R session library(reticulate)
2. 配置你的Python环境
reticulate can automatically detect Python installations on your system, but you can also specify a specific environment (like a Conda or virtualenv setup) if needed:
# Check which Python version reticulate is using py_config() # Use a specific Conda environment use_condaenv("my_conda_env", required = TRUE) # Or use a virtual environment use_virtualenv("my_virtualenv", required = TRUE)
3. 混合使用R与Python的常见方法
方法一:在R脚本中嵌入Python代码
You can run snippets of Python code directly in your R script, then access the resulting objects in R:
# Run a block of Python code py_run_string(" import pandas as pd # Create a DataFrame in Python df_python = pd.DataFrame({'col1': [1, 2, 3], 'col2': [4, 5, 6]}) ") # Access the Python DataFrame in R df_r <- py$df_python head(df_r)
Or launch an interactive Python session right from R:
# Enter Python interactive mode repl_python() # Now you can write Python code here, e.g.: # import numpy as np # my_array = np.array([10, 20, 30]) # Type `exit()` to return to R # Then access the Python object in R: py$my_array
方法二:调用Python函数(内置或自定义)
You can import Python libraries directly into R and use their functions, or define your own Python functions and call them from R:
# Import NumPy and use its mean function np <- import("numpy") np$mean(c(1, 2, 3, 4)) # Define a custom Python function py_run_string(" def add_numbers(x, y): return x + y ") # Call the Python function from R py$add_numbers(7, 3)
方法三:在R Markdown中混合代码(最流畅的协作方式)
If you're using R Markdown, you can alternate between R and Python code chunks, and even share variables between them directly:
# R chunk: Create a data frame r_df <- data.frame(a = c(1, 2, 3), b = c(10, 20, 30))
# Python chunk: Access the R data frame import pandas as pd py_df = r.r_df print(py_df)
# Python chunk: Calculate a value average_b = py_df['b'].mean()
# R chunk: Access the Python-calculated value cat("The average of column b (calculated in Python) is:", py$average_b)
4. 一些实用提示
- Make sure the Python libraries you need are installed in the environment reticulate is using (e.g., run
py_install("pandas")from R to install pandas into your active Python environment). - Data types are automatically converted between R and Python: R data frames become pandas DataFrames, R vectors become Python lists/numpy arrays, and vice versa—no manual conversion needed in most cases.
- If you run into environment issues, use
py_config()to double-check which Python version and environment reticulate is using.
内容的提问来源于stack exchange,提问作者Justí Soriano Caldentey

