【问题标题】:The paste() function and ordering levels of variablespaste() 函数和变量的排序级别
【发布时间】:2014-10-29 14:32:19
【问题描述】:

我在下面的数据框中有两列,每一列都按照特定的顺序有层次:

head(x1)
  soa congruency
1 200          9
2 102          2
3  68          1
4  68          9
5  34          9
6  68          9

head(levels(x1$soa))
[1] "34"  "68"  "102" "200"

head(levels(x1$congruency))
[1] "1" "2" "9

我希望能够粘贴两列,以便新变量的级别为:

“34_1”“34_2”“34_9”“68_1”“68_2”“68_9”等......

但是,如果我执行以下操作:

x2 <- paste(x1$soa, x1$congruency, sep = "_")

我得到的等级是:

x2 <- factor(x2)

class(x2)
[1] "factor"

levels(x2)
[1] "102_1" "102_2" "102_9" "200_1" "200_2" "200_9" "34_1"  "34_2"  "34_9" 
[10] "68_1"  "68_2"  "68_9" 

我知道我可以在粘贴列后更改级别的顺序。 但是,我希望能够对列进行排序,以便在粘贴它们之后我不需要更改级别的顺序。有没有办法可以做到这一点?例如,我尝试使用 order() 函数对 x1 进行排序(并且我做得正确),然后粘贴两列,但我仍然得到相同的级别顺序,这不是我想要的顺序。

任何帮助将不胜感激,

阿亚拉

【问题讨论】:

    标签: r paste levels


    【解决方案1】:

    你可以试试interaction:

    interaction(x1$soa, x1$congruency, sep=  "_", lex.order = TRUE)
    ## [1] 200_9 102_2 68_1  68_9  34_9  68_9 
    ## Levels: 34_1 34_2 34_9 68_1 68_2 68_9 102_1 102_2 102_9 200_1 200_2 200_9
    

    【讨论】:

    • 非常感谢!我会使用这个选项,因为它最适合我!再次感谢您!
    【解决方案2】:

    你可以试试:

     library(gtools)
     with(x1, factor(paste(soa, congruency, sep="_"),
         levels=mixedsort(unique(paste(soa, congruency, sep="_")))))
     #[1] 200_9 102_2 68_1  68_9  34_9  68_9 
     #Levels: 34_9 68_1 68_9 102_2 200_9
    

    数据

     x1 <- structure(list(soa = structure(c(4L, 3L, 2L, 2L, 1L, 2L), .Label = c("34", 
    "68", "102", "200"), class = "factor"), congruency = structure(c(3L, 
    2L, 1L, 3L, 3L, 3L), .Label = c("1", "2", "9"), class = "factor")), .Names = c("soa", 
    "congruency"), row.names = c("1", "2", "3", "4", "5", "6"), class = "data.frame")
    

    【讨论】:

      【解决方案3】:

      还在使用 paste 和 base 函数,你可以试试:

      x2<-paste(x1$soa,x1$congruency,sep="_")`
      x2<-factor(x2,levels=paste(rep(levels(x1$soa),e=nlevels(x1$congruency)),levels(x1$congruency),sep="_"))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-13
        • 2016-07-16
        • 1970-01-01
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        • 2018-01-14
        • 2021-06-15
        相关资源
        最近更新 更多