使用循环提取一系列整数
Extracting a series of integers using a loop
我有一些数据,我想从中提取整数出现的频率。这是一些示例数据:
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
我可以遍历这些并得到如下计数:
for (i in 1:5){
print(colSums(df==i))
}
但每次我尝试存储输出时都会出错。将结果输出存储在数据框中的最简洁方法是什么?我想我对通过循环存储 运行 数据的方式感到困惑。谢谢你的帮助。
我们可以使用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
).
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)
(应该更快)
table(unlist(df), rep(names(df),each=nrow(df)))
与@akrun 不同,我更喜欢尽可能使用 base R。
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
我们也可以在没有 for 循环的 base-R 中执行此操作:
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
还有一个选项:
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
我有一些数据,我想从中提取整数出现的频率。这是一些示例数据:
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
我可以遍历这些并得到如下计数:
for (i in 1:5){
print(colSums(df==i))
}
但每次我尝试存储输出时都会出错。将结果输出存储在数据框中的最简洁方法是什么?我想我对通过循环存储 运行 数据的方式感到困惑。谢谢你的帮助。
我们可以使用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
).
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)
(应该更快)
table(unlist(df), rep(names(df),each=nrow(df)))
与@akrun 不同,我更喜欢尽可能使用 base R。
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
我们也可以在没有 for 循环的 base-R 中执行此操作:
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
还有一个选项:
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