r - 根据条件和向量对列进行变异
问题描述
我有一个这样的数据框:
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 重复两次,因为进行了两次测试,我希望它们都具有相同的颜色以表明它是同一个人。B
A
#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))
解决方案
您可以使用内置颜色数据集或为您的案例创建自定义颜色数据集。我在这里使用自定义的来创建color_name
.
我们可以检查Visit_Group
using的最后一个字符endsWith
。然后我们使用match
和unique
为每个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
推荐阅读
- swift - 调整窗口大小后 NSCollectionView 的奇怪行为
- javascript - 动态下拉菜单 - 根据使用 JavaScript 选择的选项更改按钮 URL
- python - 在运行 Spark 群集的 Azure Databricks 中需要 Azure Blob 存储
- javascript - PM2 在使用 watch 选项重新启动时返回错误“spawn ps”
- android - 当应用中使用的 APK 需要较高的最低 sdk 时,如何使用最低 sdk 来支持较旧的 android 软件?
- reactjs - 无法使用 webrtc MediaDevices 在反应应用程序中切换摄像头(从前到后)
- css - 如何将 CSS 文件的 CSS 规则包含到另一个 CSS 文件的某些选择器中?
- .net-core - Dotnet Core 如何获取 JWT 标头部分?
- angularjs - 在 agularjs 的 ng-options 中选择的选项
- mysql - 删除 SQL 重复项