如何用矢量划分每个元素

时间:2017-10-30 12:53:45

标签: r

structure(list(Names = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 
3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Days = c(1L, 
2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Values = c(100L, 99L, 98L, 100L, 
99L, 98L, 100L, 99L, 98L)), .Names = c("Names", "Days", "Values"
), row.names = c(NA, -9L), class = "data.frame")

structure(list(Names = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L), class = "factor", .Label = "Master"), Days = 1:10, 
    Values = c(100L, 99L, 98L, 97L, 96L, 95L, 94L, 93L, 92L, 
    91L)), .Names = c("Names", "Days", "Values"), row.names = c(NA, 
-10L), class = "data.frame")

我有一个数据表,其值对应于每个特定样本的每一天。我有另一个数据表,它是每天比较的主值。我想将每一天从主表中除去相应的日期。

所需的输出值为百分比值。

1 个答案:

答案 0 :(得分:0)

x    <- structure(list(Names = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), .Label = c("A", "B", "C"), class = "factor"), Days = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Values = c(100L, 99L, 98L, 100L, 99L, 98L, 100L, 99L, 98L)), .Names = c("Names", "Days", "Values"), row.names = c(NA, -9L), class = "data.frame")
mstr <- structure(list(Names = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), class = "factor", .Label = "Master"), Days = 1:10, Values = c(100L, 99L, 98L, 97L, 96L, 95L, 94L, 93L, 92L, 91L)), .Names = c("Names", "Days", "Values"), row.names = c(NA, -10L), class = "data.frame")

基地R:

我们不需要Names来自后者,我更喜欢让字段名称不会发生碰撞(导致它们都以.x.y为后缀),所以我将重命名Values

mstr <- mstr[-1]
colnames(mstr)[2] <- "mVal"

直接合并会让Values与主人Values(现在为mVal)并列,所以你可以做任何你需要的数学作为直接向量: / p>

y <- merge(x, mstr[-1], by = "Days", all.x = TRUE)
y
#   Days Names Values mVal
# 1    1     A    100  100
# 2    1     C    100  100
# 3    1     B    100  100
# 4    2     A     99   99
# 5    2     B     99   99
# 6    2     C     99   99
# 7    3     B     98   98
# 8    3     A     98   98
# 9    3     C     98   98
y$newVal <- y$Values / y$mVal
y
#   Days Names Values mVal newVal
# 1    1     A    100  100      1
# 2    1     C    100  100      1
# 3    1     B    100  100      1
# 4    2     A     99   99      1
# 5    2     B     99   99      1
# 6    2     C     99   99      1
# 7    3     B     98   98      1
# 8    3     A     98   98      1
# 9    3     C     98   98      1

(我假设Days中的所有x都出现在mstr中。)

dplyr

使用上面原始/未经修改的xmstr

library(dplyr)
left_join(x, select(mstr, Days, mVal = Values), by = "Days")

让您与merge相同。 (你可以像在基本R代码中那样预先调整mstr,但我认为我会在这里作为替代方案在中间显示它。)