【问题标题】:why is my data a tuple and how can I change this so I can sort the data为什么我的数据是一个元组,我该如何更改它以便对数据进行排序
【发布时间】:2016-03-02 19:30:48
【问题描述】:

我正在使用 rpy2 通过 python 在 R 中进行一些统计分析。导入数据文件后,我想对数据进行排序并在 R 中用它做一些其他事情。导入数据并尝试对数据进行排序后,我会收到以下错误消息:

TypeError: 'tuple' object cannot be interpreted as an index

代码的最后 2 行是我尝试对数据进行排序的地方,之前的几行是我导入数据的地方。

root = os.getcwd()
dirs = [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]
for d in dirs:
    os.chdir(d)
    cwd = os.getcwd()
    files_to_analyze = (glob.glob("*.afa"))
    for f in files_to_analyze:
        afa_file = os.path.join(cwd + '/' + f)
        readfasta = robjects.r['read.fasta']
        mydatafasta = readfasta(afa_file)
        names = robjects.r['names']
        IDnames = names(mydatafasta)            
        substr = robjects.r['substr']
        ID = substr(IDnames, 1,8)
        #print ID
        readtable = robjects.r['read.table']
        gps_file = os.path.join(root + '/' + "GPS.txt")
        xy = readtable(gps_file, sep="\t")
        #print xy
        order = robjects.r['order']
        gps = xy[order(xy[:,2]),]

我不明白为什么我的数据是一个元组,而不是我可以使用 R 进一步操作的数据框。有没有办法将其转换为 R 可以使用的可行数据框?

我的 xy 数据如下所示:

Species AB425882    35.62   -83.4
Species AB425905    35.66   -83.33
Species KC413768    37.35   127.03
Species AB425841    35.33   -82.82
Species JX402724    29.38   -82.2

我想使用 R 中的 order 函数按第二列的字母数字对数据进行排序。

【问题讨论】:

  • 这会创建一个元组:order(xy[:,2]), 末尾的逗号。 order 和 xy 是什么样的?你能打印出他们的类型并给我们一个他们包含的例子吗

标签: python r rpy2


【解决方案1】:

由于该示例不足以重现您所拥有的内容,因此存在相当多的猜测。

在下文中,如果xy 是一个 R 数据框,您将需要使用专用于 R-style subsetting 的方法来执行 R-style subsetting (see the doc):

# Note R indices are 1-based while Python indices are 0-based.
# When using R-style subsetting the indices are 1-based.
gps = xy.rx(order(xy.rx(True, 2)),
            True)

【讨论】:

    猜你喜欢
    • 2017-10-03
    • 2020-08-15
    • 1970-01-01
    • 2020-04-22
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    相关资源
    最近更新 更多