Why for loop only shows result of last loop

2019-09-20 18:19发布

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?

2条回答
家丑人穷心不美
2楼-- · 2019-09-20 19:09

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

library(dplyr)
df1 %>%
   summarise_each(funs(n_distinct)) %>%
   unlist()
查看更多
乱世女痞
3楼-- · 2019-09-20 19:11

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)))
查看更多
登录 后发表回答