Why for loop only shows result of last loop

跟風遠走 提交于 2020-01-07 14:19:32

问题


I have this sample matrix:

  X1 X2 X3 X4
1  F  F  F  F
2  C  C  C  C
3  D  D  D  D
4 A# A# A#  A

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)

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?


回答1:


This should be sufficient:

y <- read.csv(file)
x <- numeric(4)
for(i in 1:4) {
    x[i] <- length(unique(y[, i]))
}

or:

x <- apply(y,2,function(x) length(unique(x)))



回答2:


You could use n_distinct (wrapper for length(unique() from dplyr

library(dplyr)
df1 %>%
   summarise_each(funs(n_distinct)) %>%
   unlist()


来源:https://stackoverflow.com/questions/29584177/why-for-loop-only-shows-result-of-last-loop

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