使用循环提取一系列整数

编程入门 行业动态 更新时间:2024-10-19 02:23:42
本文介绍了使用循环提取一系列整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一些数据要提取整数出现的频率.这是一些示例数据:

I have some data where I want to extract the frequency with which the integers appear. Here is some sample data:

df <- read.table(header=T, text="A B C D 1 1 5 3 1 2 1 2 3 2 3 2 3 5 3 4 1 4 5 3 5 3 1 4 2 6 5 2 5 1 ") df

我可以遍历这些并获得如下计数:

I can loop through these and get the counts as follows:

for (i in 1:5){ print(colSums(df==i)) }

但是每次我尝试存储输出时,都会出现错误.将结果输出存储在数据框中的最巧妙的方法是什么?我想我对循环存储数据的方式感到困惑.谢谢你的帮助.

But every time I try to store the output I get an error. What is the neatest way to store the resultant output in a dataframe? I think I'm getting confused about the way to store data that's run through a loop. Thanks for your help.

推荐答案

我们可以使用mtabulate

library(qdapTools) t(mtabulate(df)) # A B C D #1 3 1 0 2 #2 1 2 0 2 #3 1 1 2 2 #4 0 1 1 0 #5 1 1 3 0

在base R中,我们还可以unlist数据集,复制列名,并使用table(不使用任何循环,显式(for)或隐式(lapply)).

In base R, we can also unlist the dataset, replicate the column names, and use table (not using any loop, explicit (for) or implicit (lapply).

table(unlist(df),names(df)[col(df)]) # A B C D # 1 3 1 0 2 # 2 1 2 0 2 # 3 1 1 2 2 # 4 0 1 1 0 # 5 1 1 3 0

或者就像@nicola提到的那样,我们可以使用rep(应该更快)代替col(df)

Or as @nicola mentioned, the instead of col(df), we can use rep (should be faster)

table(unlist(df), rep(names(df),each=nrow(df)))

更多推荐

使用循环提取一系列整数

本文发布于:2023-11-26 13:23:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1634014.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   系列

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!