Extracting a series of integers using a loop

倾然丶 夕夏残阳落幕 提交于 2019-12-02 06:02:34

We can use 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

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

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)))

We could also do this in base-R without a for-loop:

do.call(cbind, lapply(df, function(x){table(factor(x,levels=1:6))}))

  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
6 0 0 0 0

Here's another option:

library(reshape2)
table(melt(df))
#No id variables; using all as measure variables
#        value
#variable 1 2 3 4 5
#       A 3 1 1 0 1
#       B 1 2 1 1 1
#       C 0 0 2 1 3
#       D 2 2 2 0 0
Alex W

Unlike @akrun, I prefer to use base R when possible.

out <- matrix(0, nrow= 6, ncol=4, dimnames= list(1:6, LETTERS[1:4]))
for (i in 1:6) {
  out[i,] <- unlist(lapply(df, function(j) sum(j == i)))
}

R> out
  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
6 0 0 0 0
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!