简体   繁体   English

如何将另存为RData的R中的字符向量导入到python列表中?

[英]How can I import a character vector from R saved as RData to a python list?

How can I import a character vector from R saved as RData to a python list? 如何将另存为RData的R中的字符向量导入到python列表中?

For example, if I have saved this character vector in R: 例如,如果我已将此字符向量保存在R中:

x <- c("Hello", "world!")
save (x, file = 'x.RData')

Then loaded in python with rpy2 as follows: 然后使用rpy2在python中加载,如下所示:

from __future__ import print_function
from rpy2.robjects import pandas2ri,r
import rpy2.robjects as robjects

def main():
    r['load']('x.RData')
    variables = tuple(robjects.globalenv.keys())
    print('variables: {0}'.format(variables))
    x = robjects.globalenv['x']
    print('x: {0}'.format(x))
    print('type(x): {0}'.format(type(x)))


if __name__ == "__main__":
    main()

which prints: 打印:

variables: ('x',)
x: [1] "Hello"  "world!"
type(x): <class 'rpy2.robjects.vectors.StrVector'>

How can I import it to a python list? 如何将其导入到python列表中?

You can simply cast it with list() : 您可以简单地使用list()

from __future__ import print_function
from rpy2.robjects import pandas2ri,r
import rpy2.robjects as robjects

def main():
    r['load']('x.RData')
    variables = tuple(robjects.globalenv.keys())
    print('variables: {0}'.format(variables))
    x = robjects.globalenv['x']
    print('x: {0}'.format(x))
    print('type(x): {0}'.format(type(x)))
    print('list(x): {0}'.format(list(x)))

if __name__ == "__main__":
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将R中保存为RData的数据帧导入到pandas中? - How can I import a data frame from R saved as RData to pandas? 如何将 R 的 .rdata 文件加载到 Python 中? - How to load R's .rdata files into Python? 如何在 R Markdown 中将 R 多元素向量转换为 Python 列表? - How can I convert an R multi-element vector to Python list in R Markdown? Python:如何在 CSV 导入后从列表中删除 $ 字符 - Python: How to remove $ character from list after CSV import 如何从 python 中保存为文本文件的 arrays 列表中导入和提取元素 - How to Import and extract elements from a list of arrays saved as a text file in python 如何将 Python 列表转换为列向量? - How can I convert Python list to column vector? 如何获取从 Python 3 中的模块导入的所有类的列表? - How can I get a list of all classes I import from a module in Python 3? 在 Python 中使用 readline() 时,如何从列表中删除换行符或空字符串? - How can I remove a newline character or empty string from a list when using readline() with Python? 我如何从Python列表中获取特定字符,后跟命令行参数变量 - How can i get a particular character from a Python list followed by command line argument variable 如何删除列表中项目中的字符(Python) - How can I delete a character in an item in a list (Python)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM