如何撰寫一個回圈來計算 r 中資料幀所有列中的所有元素并顯示結果?
這是我嘗試過的,但無法顯示結果:
count_1 <- for (col in colnames(df)){x = count(df, col)}
uj5u.com熱心網友回復:
假設資料框中的每個單元格只包含一個元素,而不是串列或向量本身,您可以將維度相乘。例如:
set.seed(23L)
A <- data.frame(A = rnorm(10), B = sample(LETTERS, 10), C = runif(10, 1, 3))
A
prod(dim(A))
這導致:
A B C
1 0.19321233 V 1.698088
2 -0.43468211 M 1.658262
3 0.91326710 J 2.619008
4 1.79338809 L 1.548964
5 0.99660511 X 2.878190
6 1.10749049 F 2.804534
7 -0.27808628 G 1.354106
8 1.01920549 B 2.596503
9 0.04543718 O 1.165596
10 1.57577959 N 1.571384
[1] 30
如果資料框的單元格中有向量,則它會變得更復雜一些。我們不能使用vapply或sapply使用lengthas 那只會給出表格本身的長度,而不是每個單元格內的長度。然而,rapply你的朋友在這里嗎?如果我們在串列上呼叫 rapply ,并且資料框是一種特殊的串列,我們將獲得每個單元格中的總和,所以sum(rapply(A, length))應該做你想做的。下面是一個例子:
A <- data.frame(A=double(2), B=double(2), C=character(2))
A$A <- list(c(1, 2), c(3, 4))
A$B <- list(7:9, 8:10)
A$C <- list(c('A', 'B'), c('D', 'E'))
A
A B C
1 1, 2 7, 8, 9 A, B
2 3, 4 8, 9, 10 D, E
dim(A)
[1] 2 3
vapply(A, length, integer(1L))
A B C
2 2 2
rapply(A, length)
A1 A2 B1 B2 C1 C2
2 2 3 3 2 2
sum(rapply(A, length))
[1] 14
而14是正確答案。
uj5u.com熱心網友回復:
如果你真的想做一個回圈,那么i每一列j是哪里,是列的每個元素,做
k <- 0
for(i in iris){
for(j in i){
k <- k 1
}
}
k
但最好使用nrow(df) * ncol(df)或length(df$x) * length(df)或類似的東西
uj5u.com熱心網友回復:
這里我使用了資料iris。您可以使用這樣的回圈來創建一個串列,然后為資料框中的每一列創建一個表:
freq <- vector("list", length(iris))
for (i in seq_along(iris)){
freq[[i]] <- table(iris[[i]])
}
str(freq)
List of 5
$ : 'table' int [1:35(1d)] 1 3 1 4 2 5 6 10 9 4 ...
..- attr(*, "dimnames")=List of 1
.. ..$ : chr [1:35] "4.3" "4.4" "4.5" "4.6" ...
$ : 'table' int [1:23(1d)] 1 3 4 3 8 5 9 14 10 26 ...
..- attr(*, "dimnames")=List of 1
.. ..$ : chr [1:23] "2" "2.2" "2.3" "2.4" ...
$ : 'table' int [1:43(1d)] 1 1 2 7 13 13 7 4 2 1 ...
..- attr(*, "dimnames")=List of 1
.. ..$ : chr [1:43] "1" "1.1" "1.2" "1.3" ...
$ : 'table' int [1:22(1d)] 5 29 7 7 1 1 7 3 5 13 ...
..- attr(*, "dimnames")=List of 1
.. ..$ : chr [1:22] "0.1" "0.2" "0.3" "0.4" ...
$ : 'table' int [1:3(1d)] 50 50 50
..- attr(*, "dimnames")=List of 1
.. ..$ : chr [1:3] "setosa" "versicolor" "virginica"
但也許使用泛函是更好的選擇:
lapply(iris, table)
apply(iris, 2, table)
sapply(iris, table)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/398292.html
上一篇:word不等于wordlist.readline()即使它是
下一篇:Python中的質數
