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