簡體   English   中英

如何過濾出所有列具有相同編號的行?

[英]How to filter out rows that have same number for all columns?

我想過濾出同一行中所有列中具有相同數據的數據框中的行嗎? 在此示例中,我想標識user_id 13 我怎么做?

df <- read_csv("user_id, q1, q2, q3, q4
1, 5, 5, 5, 5
2, 4, 3, 5 ,6
3, 2, 2, 2, 2
4, 5, 4, NA, 4")

目的:識別在調查表中所有問題的相同方框中打勾的人。

更新:建議的解決方案可以正常工作,直到q1具有NA。

df <- read_csv("user_id, q1, q2, q3, q4
               1, 5, 5, 5, 5
               2, NA, 3, 5 ,6
               3, 2, 2, 2, 2
               4, 5, 4, NA, 4")

您可以選擇一個問題,例如q1 ,並將其與其他問題進行比較,選擇是否所有問題都相等;

df$user_id[rowSums(df$q1 != df[-1], na.rm=T) == 0]
# [1] 1 3

df %>% filter(rowSums(.[-1] != q1, na.rm=T) == 0)

# A tibble: 2 x 5
#  user_id    q1    q2    q3    q4
#    <int> <int> <int> <int> <int>
#1       1     5     5     5     5
#2       3     2     2     2     2
  • q1列與其他帶有.[-1] != q1 q s列進行比較. 是從%>% df .[-1]刪除了user_id列;
  • 通過執行rowSums(.[-1] != q1, na.rm=T)忽略NA來檢查不等於q1的列數;
  • 如果非列不等於q1 ,則所有q s列均具有相同的編號,根據該編號進行過濾;

除非您的data.frame很大,否則可以在行上使用applyMARGIN = 1

df$user_id[apply(X = df[,-1], MARGIN = 1, FUN = function(x) length(unique(x)) == 1)]
#[1] 1 3

df[apply(X = df[,-1], MARGIN = 1, FUN = function(x) length(unique(x)) == 1),]
#  user_id q1 q2 q3 q4
#1       1  5  5  5  5
#3       3  2  2  2  2

要么

df$user_id[Reduce(function(x, y) pmax(x, y, na.rm = TRUE), df[,-1]) ==
               Reduce(function(x, y) pmin(x, y, na.rm = TRUE), df[,-1])]
#[1] 1 3

您可以使用一些基本的R代碼來解決它。

# Generate your data set
df <- data.frame(user_id =c(1,2,3,4),
                 q1 = c(5,4,2,5),
                 q2 = c(5,3,2,4),
                 q3 = c(5,5,2, NA),
                 q4 = c(5,6,2,4))

# populate the vector with a loop
test <- character(0)
for(i in 1:nrow(df)){
# check if the sum of the values is equal to the sum of the last value 
# repeated. This can only be true if all values are the same
  if(sum(df[i,2:5], na.rm = TRUE) - sum(rep(df[i,5],4)) == 0){
    test[i] <- "equal"
  } else{
    test[i] <- "not_equal"
  }

}

# finally attach the vector as a column to your data frame
df$test <- test

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM