简体   繁体   English

在 R 数据框中,对于给定的行,如何找到 A 列中的值与 B 列中的值的百分比?

[英]In an R data frame, for a given row, how can I find what percentage a value in column A is of a value in column B?

Say I have a data frame as follows:假设我有一个数据框,如下所示:

dataDF <- data.frame(
   cola = c(10, 15, 30),
   colb = c(100, 300, 800)
   )


   cola   colb
1  10     100
2  15     300
3  30     800

How can I find what percent column a row 1 (10) is of column b row 1 (100), and so on for rows 2 and 3?如何找到第 1 (10) 行是第 b 行第 1 (100) 行的百分比列,依此类推第 2 行和第 3 行?

Thanks.谢谢。

One option is prop.table and specify the margin .一种选择是prop.table并指定margin Here it is by row, so we use 1 and if it is column, it would be 2这里是按行,所以我们用1 ,如果是列,那就是2

prop.table(as.matrix(dataDF), 1)

Another way which is useful if you want to have a column containing the percentages is this:如果您想要包含百分比的列,另一种有用的方法是:

library(dplyr)

dataDF <- data.frame(
  cola = c(10, 15, 30),
  colb = c(100, 300, 800)
)
dataDF2 <- mutate(dataDF, colc = cola/colb*100)
dataDF2
  cola colb  colc
1   10  100 10.00
2   15  300  5.00
3   30  800  3.75

Another solution with data.table package :另一个带有data.table package解决方案:

library(data.table)
setDT(dataDF)[, colc := cola/colb*100]

> dataDT
   cola colb  colc
1:   10  100 10.00
2:   15  300  5.00
3:   30  800  3.75

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 R:通过了解给定行中的值来选择data.frame中的列 - R: selecting a column in data.frame by knowing a value in a given row 如何为数据框 A 中存在的列的每个唯一值在数据框 B 中创建一个新列? - How can I create a new column in a data frame B for each unique value of a column present in data frame A? 如何遍历数据框,如果找到所需的值,然后打印列和行名或索引? - How can I loop through a data frame and if I find the desired value then print the column and row name or indices? 如何使用 R 中特定行开头的百分比变化来创建新列和数据框? - How can I make a new column and data frame with the percentage change from the start of a particular row in R? R:在数据帧的列中查找大于或等于不同数据帧中列的行值的最小值 - R: Find Minimum Value in Column of Data Frame that is Greater Than or Equal to Row Value of Column in a Different Data Frame 我如何获取R中的列A值等于列B值的数据帧的子集(从CSV读取的数据) - How do i get subset of a data frame where Column A value equals Column B value in R ( Data read from CSV) R如何在数据框中按列和行计算某些值的比例 - R How to calculate a proportion of some value by column and by row in a data frame 如何找到数据框或矩阵的最小值/最大值的位置(行/列)(R问题) - How to find the location (row/column) of the minimum/maximum value of a data frame or a matrix (R question) 如何使用另一个数据框的列和行组合在 dataframe 中查找值? - How to find value in dataframe with column and row combination of another data frame? R:将数据框x中的行名与数据框y中的列名匹配,以使两个数据框共享的列中的给定变量值 - R: match row name in data frame x with column name in data frame y for a given variable value in column shared by the two data frames
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM