【问题标题】:Verifyin if there's at least two columns have the same value in a specefic column验证特定列中是否至少有两列具有相同的值
【发布时间】:2021-12-12 21:04:45
【问题描述】:

我有一个数据,我想看看我的变量是否在特定行中都具有唯一值 假设我想分析 D 行

我的数据

Name      F     S     T
A         1     2     3
B         2     3     4
C         3     4     5
D         4     5     6


> TRUE (because all the three variables have unique value)

第二个例子

Name      F     S     T
A         1     2     3
B         2     3     4
C         3     4     5
D         4     5     4

>False (because F and T have the same value in row D )

【问题讨论】:

    标签: r dataframe statistics


    【解决方案1】:

    base R

    f1 <- function(dat, ind) {
        
        tmp <- unlist(dat[ind, -1])
        length(unique(tmp)) == length(tmp)
    }
    

    -测试

    > f1(df, 4)
    [1] TRUE
    > f1(df1, 4)
    [1] FALSE
    

    数据

    df <- structure(list(Name = c("A", "B", "C", "D"), F = 1:4, S = 2:5, 
        T = 3:6), class = "data.frame", row.names = c(NA, -4L))
    df1 <- structure(list(Name = c("A", "B", "C", "D"), F = 1:4, S = 2:5, 
        T = c(3L, 4L, 5L, 4L)), class = "data.frame", row.names = c(NA, 
    -4L))
    

    【讨论】:

      【解决方案2】:

      您可以为此使用dplyr

      df %>%
        summarize_at(c(2:ncol(.)), n_distinct) %>%
        summarize(if_all(.fns = ~ .x == nrow(df)))
      

      【讨论】:

        猜你喜欢
        • 2023-04-05
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 1970-01-01
        • 2019-11-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多