Why for loop only shows result of last loop

后端 未结 2 478
没有蜡笔的小新
没有蜡笔的小新 2021-01-29 10:29

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 n

相关标签:
2条回答
  • 2021-01-29 11:14

    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)))
    
    0 讨论(0)
  • 2021-01-29 11:16

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

    library(dplyr)
    df1 %>%
       summarise_each(funs(n_distinct)) %>%
       unlist()
    
    0 讨论(0)
提交回复
热议问题