Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R中的因子水平_R_Dataframe_Factors - Fatal编程技术网

R中的因子水平

R中的因子水平,r,dataframe,factors,R,Dataframe,Factors,我有这个向量: traits <- c("resid.mean.EXT" , "resid.q75.EXT" , "resid.median.red" , "resid.q75.red" , "resid.median.yellow" , "resid.q75.yellow" , "resid.mean.norm.EXT" , "resid.q75.norm.EXT

我有这个向量:

traits <- c("resid.mean.EXT"   ,        "resid.q75.EXT"       ,     "resid.median.red"      ,   "resid.q75.red"    ,        "resid.median.yellow" ,    
            "resid.q75.yellow"  ,       "resid.mean.norm.EXT"   ,   "resid.q75.norm.EXT" ,      "resid.mean.norm.yellow"   ,"resid.median.norm.yellow",
            "resid.q75.norm.yellow"   , "resid.iqr.EXT"        ,    "resid.iqr.red"    ,        "resid.iqr.yellow"  ,       "resid.q90.EXT"   ,        
            "resid.q90.norm.red"  ,     "resid.q90.norm.yellow"   , "resid.var.EXT"     ,       "resid.q25.TOF"     ,       "resid.q25.norm.yellow" )  

traits您可以使用正则表达式和
sub
函数,例如:

## this will replace the whole string in traits with the content after the last dot
cl <- sub(".*\\.([A-Za-z]+)$", "\\1", x=traits)
factor(cl)
# [1] EXT    EXT    red    red    yellow yellow EXT    EXT    yellow yellow yellow EXT    red    yellow EXT    red    yellow EXT    TOF    yellow
# Levels: EXT red TOF yellow
##这将用最后一个点之后的内容替换traits中的整个字符串

cl这给了我一个因子向量,它的级别对应于类。我想保留原始向量
traits
,并基于
类给它4个因子级别。这种差异有意义吗?我认为这是不可能的。
因子的
级别
几乎是
唯一的(factorelations)
。我想它可以用
因子(traits,levels=c(grepl(“TOF”,traits),grepl(“EXT”,traits),grepl(“red”,traits),grep(“yellow”,traits))
但是这不起作用。我想我可能对
grepl
函数的最小不工作示例做了一些错误:
因子(c(“A1”、“A2”、“B1”),级别=c(“A”、“A”、“B”)
;但是,请参阅@akrun的答案,以了解使用名称的解决方法。@user2813055:您所请求的内容是不可能的。级别是一个字符向量,值是这些级别的整数索引,因此不能有带有子级别或子值的级别。您需要创建一个属性向量与值向量一样长的新类(这将是一个相当复杂的过程),或者需要在一个数据帧中有两个并行向量(这将非常容易)
## this will replace the whole string in traits with the content after the last dot
cl <- sub(".*\\.([A-Za-z]+)$", "\\1", x=traits)
factor(cl)
# [1] EXT    EXT    red    red    yellow yellow EXT    EXT    yellow yellow yellow EXT    red    yellow EXT    red    yellow EXT    TOF    yellow
# Levels: EXT red TOF yellow