Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/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_Character_Grepl - Fatal编程技术网

基于与R中的字符串共享的值为数据帧指定颜色

基于与R中的字符串共享的值为数据帧指定颜色,r,character,grepl,R,Character,Grepl,我在R中工作。我有许多不同的数据帧,其中包含样本名称,我正试图根据样本名称为每个数据帧中的每一行指定一种颜色。有许多行中有相同的样本名称,但我有混乱的输出数据,因此无法按样本名称排序。这是一个我所拥有的小例子 names <- c( "TC3", "102", "172", "136", "142", "143", "AC2G" ) colors <- c( "darkorange", "forestgreen", "darkolivegreen",

我在R中工作。我有许多不同的数据帧,其中包含样本名称,我正试图根据样本名称为每个数据帧中的每一行指定一种颜色。有许多行中有相同的样本名称,但我有混乱的输出数据,因此无法按样本名称排序。这是一个我所拥有的小例子

names          <- c( "TC3", "102", "172", "136", "142", "143", "AC2G" )
colors         <- c( "darkorange", "forestgreen", "darkolivegreen", "darkgreen", "darksalmon", "firebrick3", "firebrick1" )
dataA          <- c( "JR13-101A", "TC3B", "JR12-136C", "AC2GA", "TC3A" )
newcolors      <- rep( NA, length( dataA ) )
dataA          <- as.data.frame( cbind( dataA, newcolors ) )

以下是一个解决方案,它消除了1个循环:

dataA$newcolors<-as.character(dataA$newcolors)
for( j in 1:length( names ) ) {
    dataA$newcolors[grep(names[j], dataA$dataA)] <- colors[j] 
}
dataA$newcolors
dataA$newcolors<-as.character(dataA$newcolors)
for( j in 1:length( names ) ) {
    dataA$newcolors[grep(names[j], dataA$dataA)] <- colors[j] 
}