根据每个条件将多个列除以一个值

divide multiple column by a value based on each condition

我有一个具有 3 个不同条件的数据集。条件 1 内的数据需要除以 15,条件 2 和 3 内的数据需要除以 10。我尝试做 for() 以便为每个条件创建单独的数据集,然后合并这两个组(第 1 组由条件 1 组成,第 2 组由条件 2 和 3 组成)。这就是我目前对条件 1 的看法。有没有更简单的方法不需要创建子组?

Group1 <- NULL

for (val in ParticipantID) {
ParticipantID_subset_Group1 <- subset(PronounData, ParticipantID == val & Condition == "1")

I_Words_PPM <- (ParticipantID_subset_Group1$I_Words/"15")
YOU_Words_PPM <- (ParticipantID_subset_Group1$YOU_Words/"15")
WE_Words_PPM <- (ParticipantID_subset_Group1$WE_Words/"15")

df <- data.frame(val, Group, I_Words_PPM, YOU_Words_PPM, WE_Words_PPM)
Group1 <- rbind(Group1, df)
}

dim(Group1)
colnames(Group1) <- c("ParticipantID", "Condition", "I_Words_PPM", "YOU_Words_PPM", "WE_Words_PPM")
View(Group1)

没有示例数据无法完全测试此解决方案,但这应该可以满足您的要求:

# make some fake data
PronounData <- data.frame(
  ParticipantID = 1:9,
  Condition = rep(1:3, 3),
  I_Words = sample(0:20, 9, replace = TRUE), 
  YOU_Words = sample(0:40, 9, replace = TRUE), 
  WE_Words = sample(0:10, 9, replace = TRUE)
)

# if Condition 1, divide by 15
PronounData[PronounData$Condition == 1, c("I_Words_PPM", "YOU_Words_PPM", "WE_Words_PPM")] <- 
  PronounData[PronounData$Condition == 1, c("I_Words", "YOU_Words", "WE_Words")] / 15

# if Condition 2 or 3, divide by 10
PronounData[PronounData$Condition %in% 2:3, c("I_Words_PPM", "YOU_Words_PPM", "WE_Words_PPM")] <- 
  PronounData[PronounData$Condition %in% 2:3, c("I_Words", "YOU_Words", "WE_Words")] / 10

# result 
PronounData

#   ParticipantID Condition I_Words YOU_Words WE_Words I_Words_PPM YOU_Words_PPM WE_Words_PPM
# 1             1         1      17        40        6      1.1333        2.6667       0.4000
# 2             2         2      14         1        6      1.4000        0.1000       0.6000
# 3             3         3       2        34        8      0.2000        3.4000       0.8000
# 4             4         1       0        33        1      0.0000        2.2000       0.0667
# 5             5         2       4        15        0      0.4000        1.5000       0.0000
# 6             6         3       1         7        6      0.1000        0.7000       0.6000
# 7             7         1       6        10        1      0.4000        0.6667       0.0667
# 8             8         2       1        33        9      0.1000        3.3000       0.9000
# 9             9         3       9        40        0      0.9000        4.0000       0.0000

注意,R 是建立在矢量化运算之上的,因此遍历每一行很少是最佳解决方案。相反,您通常希望找到一种一次性修改整个 vectors/columns 或至少其中一部分的方法。这通常会更快更简单。