【问题标题】:Rescale the values for sum of numbers in R重新调整 R 中数字总和的值
【发布时间】:2021-05-31 11:01:52
【问题描述】:

如果我有这些数据框

df1<- as.numeric(c("20", "25", "15", "50"))

df2<- as.numeric (c("15", "20", "10", "5"))

df3<- as.numeric(c("10", "7", "15", "13"))

my_list <- list(df1, df2, df3)

sum_dat <- as.numeric(c("180", "90", "5"))

这里我希望列表 my_list 中的数据帧,即重新调整 df1 中的数字,使 df1 (20+25+15+50) 的总和接近或等于 180,df2 总和等于 90 , df 3 总和等于 5。

【问题讨论】:

  • 代码中的df1是什么
  • 您的代码显示character 类向量:因为您使用c(),它们是向量而不是数据框,并且因为您在数字周围使用引号,所以它们是character 而不是numeric 类。
  • 我的错。我已经更新了问题

标签: r list data-manipulation rescale


【解决方案1】:

我们可以使用Map(假设vector都是numeric

my_list_rescaled <- Map(function(x, y)  x * y/sum(x), my_list, sum_dat)

【讨论】:

    【解决方案2】:

    另一个使用 asplit + list2DF + colSums 的基本 R 选项

    asplit(t(t(df <- list2DF(my_list)) / colSums(df) * sum_dat), 2)
    

    给予

    [[1]]
    [1] 32.72727 40.90909 24.54545 81.81818
    
    [[2]]
    [1] 27 36 18  9
    
    [[3]]
    [1] 1.1111111 0.7777778 1.6666667 1.4444444
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 2023-03-30
      • 2021-08-15
      • 1970-01-01
      相关资源
      最近更新 更多