【问题标题】:Targetting a column with a variable (R)使用变量 (R) 定位列
【发布时间】:2018-07-24 11:59:46
【问题描述】:

我的英语不好,很抱歉;)

我目前正在 r 上编写一些小东西。

我在 R 上的数据框(名为 data.frame)中有很多列。

列的名称是1A,1B,2A,2B,3A,3B,.......

我想对每一列(1A 与 1B)进行 t 检验,...

我的命令是

t.test(data.frame$`1A`,data.frame$`1B`, paired=T,alternative="two.sided")

我想过使用命令 for(i in 1:100),并将变量 i 用于列名,但我不知道如何将变量放入列名(我试过 data. frame$i'A' 和其他东西,它没有工作......)

如果你有任何想法,我会接受;)

非常感谢

【问题讨论】:

    标签: r for-loop command repeat


    【解决方案1】:

    尝试:

      for (i in 1:X){
      t<-t.test(data[,paste(i,"A",sep="")],data[,paste(i,"B",sep="")],    
      paired=T,alternative="two.sided")
      print(t)
      }
    

    (我把data中data.frame的名字改了,免得大家弄糊涂了)

    【讨论】:

    • 您应该将X 更改为seq_along(data)
    • 我想过,但由于列号与循环变量不同,我选择了简单的方法;)(我从 1:100 -> 具有 200 列的数据框)'length(colnames (t))/2' 是可能的。
    【解决方案2】:

    试试这个

    #Create sample dataset
    
    `1A`<-sample(1:1000, 1000)
    `1B`<-sample(1:1000, 1000)
    `2A`<-sample(1:1000, 1000)
    `2B`<-sample(1:1000, 1000)
    
    table1<-data.frame(`1A`,`1B`,`2A`,`2B`)
    
    
    #Generate nested do loop for all compinations of pairs
    for (i in 1:ncol(table1)) {
      for (j in 1:ncol(table1))  {
    
        txt=paste0("t.test(table1$",names(table1[i]),",table1$",names(table1[j]),",paired=T,alternative='two.sided')")
    
        t<-eval(parse(text = txt))
        print(t)
    
      }
    }
    

    【讨论】:

      【解决方案3】:

      非常感谢您的帮助!

      我主要使用 Martin 方法:这对我有用:

      for(i in 1:(ncol(data.frame)/2)){
      a<-data.frame[,paste(i,"A",sep="")]
      #the problem  was the creation each time of a new data.frame (witch was a, with one colomn, the good one, bur the colomn name didnt change.... i rename it
      names(a)[1]<-"A"
      b<-data.frame[,paste(i,"B",sep="")]
      names(b)[1]<-"B"
      t.test(a$'A',b$`B`, paired=T,alternative="two.sided")
      }
      

      非常感谢!!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-08-15
        • 1970-01-01
        • 2017-10-24
        • 2022-01-15
        • 2018-06-13
        • 1970-01-01
        相关资源
        最近更新 更多