I have a list of data frames each containing 3 columns,
df.1 <- data.frame(data=cbind(rnorm(5, 0), rnorm(5, 2), rnorm(5, 5)))
df.2 <- data.frame(data=cbind(rnorm(5, 0), rnorm(5, 2), rnorm(5, 5)))
names(df.1) <- c("a", "b", "c")
names(df.2) <- c("a", "b", "c")
ls.1<- list(df.1,df.2)
names(ls.1) <- c("cat", "dog")
ls.1
Now I also have another list containing 3 columns.
df.1 <- data.frame(data=cbind(rnorm(5, 0), rnorm(5, 2), rnorm(5, 5)))
df.2 <- data.frame(data=cbind(rnorm(5, 0), rnorm(5, 2), rnorm(5, 5)))
names(df.1) <- c("a", "b", "c")
names(df.2) <- c("a", "b", "c")
ls.2<- list(df.1,df.2)
names(ls.2) <- c("cow", "pig")
ls.2
I want to compare column b of cat with column b of cow*, and if the entire value of columns are equal say TRUE
else FALSE
for the column and then move on to compare
column b of dog with column b of pig*. The value return will be a single TRUE
if all the values of the compared columns are same or a single FALSE
. If I have 5 dataframe in a list I should have 5 TRUE
or FALSE
.
I tried this, but it did not work.
chcfunc <- function(a,b){(ifelse(a[[,2]]==b[[,2]],FALSE,TRUE))}
chc <- lapply(ls.1,ls.2,chcfunc)
CodePudding user response:
If we want to compare the 'b' columns in corresponding list
elements, use Map
from base R
Map(function(x, y) all(x$b == y$b, na.rm = TRUE), ls.1, ls.2)
Or use setequal
Map(setequal, ls.1, ls.2)
Or with map2
from purrr
library(purrr)
map2(ls.1, ls.2, ~ all(.x$b == .y$b, na.rm = TRUE))