如何使用数据表格创建一个新表格,显示满足条件的行的比例?

huangapple go评论54阅读模式
英文:

How to use data table to create a new table which shows proportion of rows which meet condition?

问题

我尝试使用数据表格来查看每列有多少行符合条件(作为总行数的比例),并将其显示在输出表格中,因此每列都有一个此值的观测。例如,作为输入

 结构(列表(A = c(57L,546L,3245L,34L,356L),B = c(24L,
 65L,5678L,453L,32L),C = c(567L,4328L,56789L,2345L,654L
  ),D = c(987L,456L,786L,23975L,21L),E = c(345L,678L,3456L,
   89L,234L)),class =“data.frame”,row.names = c(NA,-5L))

我一直在尝试使用以下方法,但没有太大成功:

   df1 <- as.data.table(df)

   out <- df1[, sapply(.SD, function(x) c(any(x <= 60)/.N))]

我希望输出类似于以下内容,针对每个条件:

      <=60
          A    B    C    D    E
         0.4  0.4   0   0.2   0

     >60& <1000
         A     B     C     D     E
         0.4  0.4   0.2   0.6   0.8

任何指导都将不胜感激。

英文:

I'm trying to use data table to see per column, how many rows meet a condition (as a proportion of total number of rows) and to have this in an output table, so there is 1 obs per column with this value. For example, as input

 structure(list(A = c(57L, 546L, 3245L, 34L, 356L), B = c(24L, 
 65L, 5678L, 453L, 32L), C = c(567L, 4328L, 56789L, 2345L, 654L
  ), D = c(987L, 456L, 786L, 23975L, 21L), E = c(345L, 678L, 3456L, 
   89L, 234L)), class = &quot;data.frame&quot;, row.names = c(NA, -5L))

I've been trying to use the below without much success:

   df1 &lt;- as.data.table(df)

   out &lt;- df1[, sapply(.SD, function(x) c(any(x &lt;= 60)/.N))]

I would like the output to be something like this for each condition:

      &lt;=60
          A    B    C    D    E
         0.4  0.4   0   0.2   0

     &gt;60&amp; &lt;1000
         A     B     C     D     E
         0.4  0.4   0.2   0.6   0.8

Any direction would be appreciated.

答案1

得分: 2

以下是已翻译的内容:

一种解决您的问题的方法:

df[, lapply(.SD, function(x) c(sum(x<=60), sum(x>60 & x<1000))/.N)]

       A     B     C     D     E
1:   0.4   0.4   0.0   0.2   0.0
2:   0.4   0.4   0.4   0.6   0.8
英文:

One way to solve your problem:

df[, lapply(.SD, function(x) c(sum(x&lt;=60), sum(x&gt;60 &amp; x&lt;1000))/.N)]

	   A     B     C     D     E
1:   0.4   0.4   0.0   0.2   0.0
2:   0.4   0.4   0.4   0.6   0.8

huangapple
  • 本文由 发表于 2023年5月7日 23:56:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定