2017-02-25 26 views
2

我在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的循环,但我还没有打破习惯。
这是我试过的。可能是一些显而易见的,但我只是得到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 ] 
    } 
    } 
} 

回答

1

这里是一个解决方案,从而消除了1圈:

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

的newcolors列转换为字符,而不是一个因素使得更新更容易。如果名称的数量很短,那么单循环应该不会有太大的性能影响。

相关问题