我在python中的rpy2中有一个数据帧,我想从中提取列。这个R代码的rpy2等价物是什么?
df[,c("colA", "colC")]
这可以获得第一列:
mydf.rx(1)
但是如何拉出一组列,例如第1,第3和第5?
mydf.rx([1,3,5])
不起作用。也没有:
mydf.rx(rpy2.robjects.r.c([1,3,5]))
答案 0 :(得分:5)
或者,您可以将R数据帧传递到Python pandas数据框中,并对生成的1,3,5列进行子集化:
#!/usr/bin/python
import rpy2
import rpy2.robjects as ro
import pandas as pd
import pandas.rpy.common as com
# SOURCE R SCRIPT INSIDE PYTHON
ro.r.source('C:\\Path\To\R script.R')
# DEFINE PYTHON DF AS R DF
pydf = com.load_data('rdf')
cols = pydf[[1,3,5]]
答案 1 :(得分:2)
我认为答案是:
# cols to select
c = rpy2.robjects.IntVector((1,3))
# selection from df
mydf.rx(True, c)
答案 2 :(得分:0)
我找到的最好的方法就是做这个简单的事情:
from rpy2.robjects.packages import importr
from rpy2.robjects import pandas2ri
import rpy2.robjects as robjects
dataframe = robjects.r('data.frame')
df_rpy2 = dataframe([1,2,],[5,6])
df_pd = pd.DataFrame({'A': [1,2], 'B': [5,6]})
base = importr('base') #Creates an instance of R's base package
pandas2ri.activate() #Converts any pandas dataframe to R equivalent
base.colnames(df_pd) #Finds the column names of the dataframe df_pd
base.colnames(df_rpy2) #Finds the column names of the dataframe df_rpy2
输出结果为:
R object with classes: ('character',) mapped to:
<StrVector - Python:0x7fa3504d3048 / R:0x10f65ac0>
['X1L', 'X2L', 'X5L', 'X6L']
R object with classes: ('character',) mapped to:
<StrVector - Python:0x7fa352493548 / R:0x103b6e40>
['A', 'B']
这适用于使用pandas&amp; amp;创建的数据帧。 rpy2。希望这有帮助!