首页 > 解决方案 > 根据条件和向量对列进行变异

问题描述

我有一个这样的数据框:

df <- tribble(~ `ProbandID`, ~ `Visit_Group`,
       "1", "V1-B",
       "4", "V2-A",
       "1", "V2-B",
       "2", "V1-A",
       "3", "V2-B",
       "2", "V2-A",
       "4", "V1-A",
       "3", "V1-B")

基本上,这是一个标准的事后测试设计,参与者被随机分配到两个臂,这里是“A”和“B”,并在两次访问(干预前和干预后)进行测量,这里是 V1 和 V2。

我已将它们连接成一Visit_Group列。

我现在想有一个基于颜色值的列,这样任何唯一的只有当它是分组的一部分并且所有s 都被普遍分配给某个恒定颜色时才会ProbandID获得唯一的颜色。在这里,相同的先证者 ID 重复两次,因为进行了两次测试,我希望它们都具有相同的颜色以表明它是同一个人。BA

#Expected output - all A's assigned to a constant colour - black 
# and all the participants in B get a unique colour which is the same across both the visits (`ProbandID` 1 is gold and 3 is green)

df_res <- tribble(~ `ProbandID`, ~ `Visit_Group`, ~ `colors`,
       "1", "V1-B", "gold",
       "4", "V2-A", "black",
       "1", "V2-B", "gold",
       "2", "V1-A", "black",
       "3", "V2-B", "green",
       "2", "V2-A", "black",
       "4", "V1-A", "black",
       "3", "V1-B", "green")

我想出了一个相当不雅的答案,任何建议/答案将不胜感激。

我不优雅的解决方案:

# filter out Group B and add a column with desire colour vector
m <- df %>% 
  select(Group, Proband.ID) %>% 
  filter(Group Group == "B") %>% 
  unique() %>% 
  mutate(cols = col_vector[1:17]) 

#filter out group A
s <- t %>% 
  select(Group, Proband.ID) %>% 
  filter(Group == "A") %>% 
  unique() 

# make a list containing the colour vector from `m` data frame and add empty strings to the size of "A" Proband's
mm <- list(prob = c(m$cols, (rep("",length(s$Proband.ID)))))

# name the list by concatenating in order and use this list in pheatmap annotatioin
names(mm$prob) <- c(as.character(m$Proband.ID), as.character(s$Proband.ID))

标签: rdataframedplyr

解决方案


您可以使用内置颜色数据集或为您的案例创建自定义颜色数据集。我在这里使用自定义的来创建color_name.

我们可以检查Visit_Groupusing的最后一个字符endsWith。然后我们使用matchunique为每个ProbandID用于子集的唯一索引号color_name。默认情况下,所有“A”值都获得第一个索引,即“黑色”颜色。

color_name <- c('Black', 'red', 'blue', 'orange', 'green')

new_df <- df %>%
           mutate(color = color_name[ifelse(endsWith(Visit_Group, 'A'), 1, 
                          match(ProbandID, unique(ProbandID)) + 1)])
new_df
# ProbandID Visit_Group color
#  <chr>     <chr>       <chr>
#1 1         V1-B        red  
#2 4         V2-A        Black
#3 1         V2-B        red  
#4 2         V1-A        Black
#5 3         V2-B        green
#6 2         V2-A        Black
#7 4         V1-A        Black
#8 3         V1-B        green

推荐阅读