paste()函数和变量的排序级别

时间:2014-10-29 14:32:20

标签: r paste levels

我在以下数据框中有两列,每列都有根据特定顺序的级别:

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(我正确地做了),然后粘贴两列,但我仍然得到相同的级别顺序,这不是我想要的顺序。

非常感谢任何帮助,

阿亚拉

3 个答案:

答案 0 :(得分:7)

您可以尝试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

答案 1 :(得分:1)

你可以尝试:

 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")

答案 2 :(得分:0)

仍然使用粘贴和基本功能,您可以尝试:

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