根据R中的字符串,基于共享值分配颜色



我在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 ) )

我已经尝试了以下内容(我知道循环,但这就是我想做的)。我也试图摆脱R中的循环,但我还没有习惯。
这是我尝试的。可能很明显,但我只是让所有newcolors返回NA

for( i in 1:nrow( dataA ) ) {
  for( j in 1:length( names ) ) {
    if( grepl( dataA$dataA[ i ], names[ j ] ) ) {
   dataA$newcolors[ i ]  <- colors[ j ] 
    }
  }
}

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

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

将NewColors列转换为字符而不是因素,使更新更加容易。如果名称的数量很短,则单个循环不应有太大的性能影响。