David Z
David Z

Reputation: 7051

How to check identical for multiple R objects?

Suppose I have a list object such like:

set.seed(123)
df <- data.frame(x = rnorm(5), y = rbinom(5,2,0.5))
rownames(df) <- LETTERS[1:5]
ls <- list(df1 = df, df2 = df, df3 = df)

My question is how to quickly check the row names are identical across the three elements (data frames) in the ls.

Upvotes: 1

Views: 263

Answers (2)

konvas
konvas

Reputation: 14366

You can try

all(sapply(ls, rownames) == rownames(ls[[1]]))

To check only the name of the ith column, you can modify this to

all(sapply(ls, rownames)[i, ] == rownames(ls[[1]])[i])

Upvotes: 3

Lorenzo Rossi
Lorenzo Rossi

Reputation: 1481

You can get a list of row names with:

Map(rownames, ls)

so you can check that all the dataframes have the same rownames checking that there is only one unique value of row.names vector with:

length(unique(Map(rownames, ls))) == 1

Upvotes: 1

Related Questions