我在 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 中的循环,但我还没有改掉这个习惯。
这是我尝试过的。可能是显而易见的事情,但我只是明白NA
返回所有newcolors
for( i in 1:nrow( dataA ) ) {
for( j in 1:length( names ) ) {
if( grepl( dataA$dataA[ i ], names[ j ] ) ) {
dataA$newcolors[ i ] <- colors[ j ]
}
}
}