如何将数据帧的正元素除以特定数据帧列,将负元素除以另一个?

问题描述 投票:1回答:1

如何将数据帧行的正值除以特定列,将相同数据帧行的负值除以另一个特定列?

This is the data frame head.

例如:我需要将第一行的所有值除以“资产”列,因为它们都是正数。

在第二行,所有值都需要除以“Assets”列,但是与“RoW”列相关联的值,因为它是行的唯一负值。

有什么建议?

r dataframe
1个回答
0
投票

假设数据帧是df。那么以下应该做你想要的:

apply(df, FUN=function(x) ifelse(x > 0, x / df$Assets, x / df$Whatever), MARGIN=2)

它迭代所有列(MARGIN=2中的apply)并将给定函数应用于所有列。在每列中,正条目除以Assets列中的对应值,非正值除以Whatever列中的对应值。

例:

> df <- data.frame(Profit=c(1000,-1000,2000,-2000),
                 Assets=c(1,2,3,4), Whatever=c(-10,-20,-30,-40))

> df

   Profit Assets Whatever
 1   1000      1      -10
 2  -1000      2      -20
 3   2000      3      -30
 4  -2000      4      -40

> apply(df, FUN=function(x) ifelse (x > 0, x / df$Assets,
    x / df$Whatever), MARGIN=2)

         Profit Assets Whatever
 [1,] 1000.0000      1        1
 [2,]   50.0000      1        1
 [3,]  666.6667      1        1
 [4,]   50.0000      1        1
© www.soinside.com 2019 - 2024. All rights reserved.