【问题标题】:As.vector does not convert data.frame subset to vectorAs.vector 不会将 data.frame 子集转换为向量
【发布时间】:2012-12-05 02:51:15
【问题描述】:

下面我提供了一些我一直在处理的代码的 sn-p。我已经成功地将字符串作为表格阅读。我希望在我的表的某些子集上使用 median() 函数。根据我所做的研究和我自己的经验,median() 没有为 data.frame 或 data.frame 的子集定义行为。因此,为了让我的问题适合某些已定义的行为,我尝试将我想要的子集转换为向量。但是,即使在使用 as.vector 转换我想要的子集之后,我仍然有一个 data.frame。当我尝试对此调用中位数时,我得到“参数不是数字或逻辑:返回 NA。”

我自己玩过很多次,并试图在这里和其他地方找到信息。作为说明,我已经尝试了此线程R-friendly way to convert R data.frame column to a vector? 上的可接受解决方案中列出的方法,并取得了与我现在相同的结果。我不太在乎我是如何做到这一点的;欢迎提出其他方法。

感谢您的宝贵时间。

for(i in 1:length(text_array)){
    temp= read.table(textConnection(text_array[i]), sep="\t",row.names=NULL, header= FALSE,  fill=TRUE) 
    value=""
    #we are now going to process temp and add it
    cur_DS=coll_data_sets[i]
    #median is the value that we are going to insert into the result array.
    #currently the logic behind it is not implemented.
    #the value will be the median of state1 divided by the median of state2.
    t_states=vector(length=ncol(temp))
    for(j in 1:ncol(temp)){
        t_states[j]=toString(temp[2,j])

    }
    t_states=(unique(t_states))
    #this logic is current is set to reject data from more than one state.
    # It will also reject anything that appears to lack state data.
    if(length(t_states) !=  2){
        value=NA
    }else{
        s1_expr=as.vector(x=(temp[3, temp[2,]==t_states[1]]))
        s2_expr=as.vector(x=temp[3, temp[2,]==t_states[2]])
        print(class(s1_expr))
    #   med1= (median(s1_expr))
    #   med2= (median(s2_expr))
    #   if(is.na(med1[1]) || is.na(med2[1])){
    #       value=-1
        }#else{
    #       value=med1[1]/med2[1]
    #       print(value)
    #   }

    }
[1] "data.frame"
[1] "data.frame"
[1] "data.frame"

这里是 'temp' 的示例值:

         V1        V2          V3          V4
1 GSM506899 GSM506900   GSM506901   GSM506902
2 wild type wild type Zbtb20 null Zbtb20 null
3      99.3     98.24        66.2      102.42
4      55.8     20.11        22.9       16.98
5     159.6     63.46       102.5       67.17
6       166     54.73         215       49.46

【问题讨论】:

  • 请发布一个可重现的示例。你的数据是什么样的? 以表格形式读取字符串是什么意思?我正在描绘tatting
  • @mnel 将字符串读取为表格,我的意思是:read.table(textConnection(text_array[i]), sep="\t",row.names=NULL, header= FALSE, fill=TRUE). Basically using text connections rather than files. 我主要提到这一点,因为很多人不熟悉该功能。我将编辑问题以显示我的数据是什么样的。
  • 您的数据似乎没有正确读入。您的前两行是否真的是列名,然后显示数据。 data.frame 不会处理这个问题。

标签: r vector casting dataframe


【解决方案1】:

数据框是列表。即使您只选择了一行数据,它仍然是一个列表。

试试unlist。 (假设您的“行”中的所有值当然都是数字。如果不是,那么您有更大的问题。)

【讨论】:

  • 感谢您提醒我一些简单的事情。使用 unlist 解决了这个问题。不,我并没有试图找到字符串的中位数或任何类似的东西——我发誓只是浮动。再次感谢。
  • 我实际上认为这是一个经典的 R 陷阱/“WTF”机会:值得在stackoverflow.com/questions/1535021/… 下提交以防混淆,尽管解决方法非常简单。
猜你喜欢
  • 2011-10-27
  • 2013-05-24
  • 2020-06-21
  • 2011-06-20
  • 1970-01-01
  • 2017-08-25
相关资源
最近更新 更多