how to select row names and row for any mismatch found in a row data frame

Viewed 88

I have a data frame like this in R

df <- data.frame(V1=c("L", "L", "P", "P"), V2=c("M", "M", "M" , "M"), V3=c("X", "X", "X", "X" ), V4=c( "V","V","V","V"))

I would like to subset this data frame based on the mismatches found by row and create two different tables like this

df1 
  V1 V2 V3 V4
1  L  M  X  V
2  L  M  X  V

df2
V1 V2 V3 V4
1 P  M  X  V
2 P  M  X  V

I know that can be done by split(df, df$V1) but I would like to know if there is a more "automatic" way in which I do not have to specify the col with mismatches Thank you!

4 Answers

In base R, you could use:

split(df, do.call(paste, df))

$`L M X V`
  V1 V2 V3 V4
1  L  M  X  V
2  L  M  X  V

$`P M X V`
  V1 V2 V3 V4
3  P  M  X  V
4  P  M  X  V

You can use df directly in split (Thanks to @27-ϕ-9 for the comment!)

split(df, df)
#$L.M.X.V
#  V1 V2 V3 V4
#1  L  M  X  V
#2  L  M  X  V
#
#$P.M.X.V
#  V1 V2 V3 V4
#3  P  M  X  V
#4  P  M  X  V

Or use it with interaction in split:

split(df, interaction(df))
#$L.M.X.V
#  V1 V2 V3 V4
#1  L  M  X  V
#2  L  M  X  V
#
#$P.M.X.V
#  V1 V2 V3 V4
#3  P  M  X  V
#4  P  M  X  V

a data.table option is

library(data.table)
split(setDT(df), by = names(df))

# $L.M.X.V
#    V1 V2 V3 V4
# 1:  L  M  X  V
# 2:  L  M  X  V
# 
# $P.M.X.V
#    V1 V2 V3 V4
# 1:  P  M  X  V
# 2:  P  M  X  V

dplyr option -

library(dplyr)
df %>% group_by(across()) %>% group_split()

# A tibble: 2 x 4
#  V1    V2    V3    V4   
#  <chr> <chr> <chr> <chr>
#1 L     M     X     V    
#2 L     M     X     V    

#[[2]]
# A tibble: 2 x 4
#  V1    V2    V3    V4   
#  <chr> <chr> <chr> <chr>
#1 P     M     X     V    
#2 P     M     X     V    
Related