gpt4 book ai didi

R:将选定列中的值添加到大量其他列

转载 作者:行者123 更新时间:2023-12-04 16:36:11 25 4
gpt4 key购买 nike

我对 R 比较陌生,有一个如下所示的数据框:

df <- structure(list(row.names = 1:5, date = c("01-01-2017", "10-01-2017", 
"10-04-2017", "11-04-2017", "12-04-2017"), fixed_factor = c(NA,
3L, 2L, 5L, 10L), line_1_rec_1_mean = c(0.5, 0.1, 0.05, 0.05,
0.1), line_1_rec_2_mean = c(6, 5, 3, 2, 0.9), line_1_rec_3_mean = c(88L,
3L, 4L, 3L, 7L), line_1_rec_5_mean = c(6, 0.2, 0.7, 0.6, 3),
line_1_rec_6_mean = c(50L, 1L, 5L, 8L, 2L)), row.names = c(NA,
-5L), class = "data.frame")
  row.names       date fixed_factor line_1_rec_1_mean line_1_rec_2_mean line_1_rec_3_mean line_1_rec_5_mean line_1_rec_6_mean
1 1 01-01-2017 NA 0.5 6 88 6 50
2 2 10-01-2017 3 0.1 5 3 0.2 1
3 3 10-04-2017 2 0.05 3 4 0.7 5
4 4 11-04-2017 5 0.05 2 3 0.6 8
5 5 12-04-2017 10 0.1 0.9 7 3 2

真实数据框包含超过 1,500 列和 365 行。

我想做的是将每一行的“fixed_factor”添加到所有“line_1_rec*”列。这是除前三列之外的所有列,并将生成的数据集保存为一个新的数据框,看起来像这样:

 row.names       date fixed_factor line_1_rec_1_mean line_1_rec_2_mean line_1_rec_3_mean line_1_rec_5_mean line_1_rec_6_mean
1 1 01-01-2017 NA 0.50 6.0 88 6.0 50
2 2 10-01-2017 3 3.10 8.0 6 3.2 4
3 3 10-04-2017 2 2.05 5.0 6 2.7 7
4 4 11-04-2017 5 5.05 7.0 8 5.6 13
5 5 12-04-2017 10 10.10 10.9 17 13.0 12

我读了很多书,但没有设法找到解决方案。任何帮助将不胜感激。

最佳答案

您可以使用dplyr。有一种方法可以同时更改(或 mutate)多个列。您可以使用 across 指定相关列。请注意,我使用 coalescefixed_factor 中的 NA 替换为 0。

library(dplyr)

df %>%
mutate(across(matches("line_1_rec"), ~.x + coalesce(fixed_factor, 0)))

关于R:将选定列中的值添加到大量其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69569522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com