为什么for循环仅显示最后一个循环的结果 [英] Why for loop only shows result of last loop
本文介绍了为什么for循环仅显示最后一个循环的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个样本矩阵:
X1 X2 X3 X4
1 F F F F
2 C C C C
3 D D D D
4 A# A# A# A
我正在尝试使用一个for循环,以获得每列中唯一间距的数量。这是我试图这样做的:
And I'm trying to use a for loop to get the number of unique pitches in each column. Here's how I'm trying to do it:
y <- read.csv(file)
frame <- data.frame(y)
for(i in 1:4){
specframe <- frame[, i]
x <- unique(specframe)
}
length(x)
但长度的结果只是4.输出I' m寻找是4个元素的向量,其中每个元素详细说明了各自列中唯一元素的数量。看起来像for循环每次循环都会重写x,那么如何在每次循环的时候做一个包含一个元素的向量?
But the result of length is just 4. The output I'm looking for is a vector of 4 elements in which each element details the number of unique elements in their respective columns. It looks like the for loop is rewriting x every time it loops, so how would I make a vector which contains an element for each time it loops?
推荐答案
这应该是足够的:
y <- read.csv(file)
x <- numeric(4)
for(i in 1:4) {
x[i] <- length(unique(y[, i]))
}
或:
x <- apply(y,2,function(x) length(unique(x)))
这篇关于为什么for循环仅显示最后一个循环的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文