【问题标题】:Fill in values of a variable based on another variable in the same dataframe + another smaller dataframe根据同一数据帧中的另一个变量+另一个较小的数据帧填充变量的值
【发布时间】:2020-11-14 11:34:17
【问题描述】:

我有两个数据框:

名为df的主数据框:

    variable     value n p
1          1 0.4457915 0 0
2          1 0.3573796 0 0
3          1 0.4809338 0 0
4          7 0.4707770 0 0
5          2 0.4617186 0 0
6          1 0.4330623 0 0
7          1 0.4426557 0 0
8          1 0.5265566 0 0
9          1 0.4606076 0 0
10         3 0.4150958 0 0
11         1 0.4459441 0 0
12         1 0.4143590 0 0
13         1 0.4344068 0 0
14         5 0.3259516 0 0
15         1 0.4202466 0 0
16         1 0.3120299 0 0
17         1 0.3938266 0 0
18         1 0.5133825 0 0
19         1 0.3331676 0 0
20         1 0.5563704 0 0

另一个较小的数据框称为cheatsheat

    X1    X2
1   10 0.000
2   10 0.200
3   10 0.800
4   10 0.999
5   30 0.000
6   30 0.200
7   30 0.800
8   30 0.999
9  100 0.000
10 100 0.200
11 100 0.800
12 100 0.999
13 200 0.000
14 200 0.200
15 200 0.800
16 200 0.999

我尝试完成的是根据变量“变量”填写主数据帧df中的n和p(范围从1到16,与数据帧cheatsheat中的行数相同) ) 以及日期帧 cheatsheat 中 X1 和 X2 的值。

这意味着输出应该是这样的:

    variable     value  n   p
1          1 0.4457915 10 0.0
2          1 0.3573796 10 0.0
3          1 0.4809338 10 0.0
4          7 0.4707770 30 0.8
5          2 0.4617186 10 0.2
6          1 0.4330623 10 0.0
7          1 0.4426557 10 0.0
8          1 0.5265566 10 0.0
9          1 0.4606076 10 0.0
10         3 0.3201487 10 0.8
11         1 0.4459441 10 0.0
12         1 0.4143590 10 0.0
13         1 0.4344068 10 0.0
14         5 0.3259516 30 0.0
15         1 0.4202466 10 0.0
16         1 0.3120299 10 0.0
17         1 0.3938266 10 0.0
18         1 0.5133825 10 0.0
19         1 0.3331676 10 0.0
20         1 0.5563704 10 0.0

我已经通过以下 for 循环完成了这项工作:

  for (i in 1:nrow(df)) {
    df[i, "n"] <- cheatsheat[df[i, "variable"], "X1"]
    df[i, "p"] <- cheatsheat[df[i, "variable"], "X2"]
  }

但是,你们在主数据框中只看到 20 行,而实际上我有超过 200000 行。这意味着完成脚本需要很长时间。你们知道我如何可以完成与 for 循环相同但没有 for 循环本身的操作吗?我知道矢量化可能有助于解决这个问题。我已经在 StackOverflow 上寻找了几个小时的答案,但我找不到答案。任何帮助表示赞赏!

【问题讨论】:

  • 这有帮助吗:cbind(df1[, c("variable", "value")], df2[df1$variable,]) ?

标签: r vectorization reshape tidyr reshape2


【解决方案1】:

您可以使用match 函数解决您的问题。

variableMatchIndices <- match(df$variable,1:NROW(cheatsheat))

现在您可以通过这些索引访问cheatsheat 来填写您的df

df$n <- cheatsheat[variableMatchIndices ,1]
df$p <- cheatsheat[variableMatchIndices ,2]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多