oercim
oercim

Reputation: 1848

Frequencies in a specific column of data frames in a list - R

Let I have a list that consists of data frames(df1, df2, ..dfn).

Each data frame has a column named head1 which consist binary elements(0 and 1).

For example

list1[[1]]$head1 is 11010001

list1[[2]]$head1 is 1000100000

where list1[[1]] is df1 and list1[[2]] is df2.

I want to get a data frame, which returns proportion of 1's in the head column of each data frame of the list1.

For the above example:

df[1,]=0.5  

(four 0's and four 1's)

df[2,]=0.2  

(eight 0's and two 1's)

How can I do that using R? I will be very glad for any help. Thanks a lot.

Upvotes: 0

Views: 52

Answers (1)

mtoto
mtoto

Reputation: 24178

We can use lapply() in combination with mean() to get the proportion of 1's in the same column in a list of data.frame's.

lapply(list1, function(x) mean(x[,"head1"]))
#$df1
#[1] 0.5
#
#$df2
#[1] 0.2

Data

list1 <- structure(list(df1 = structure(list(head1 = c(1, 1, 0, 1, 0, 
0, 0, 1)), .Names = "head1", row.names = c(NA, -8L), class = "data.frame"), 
    df2 = structure(list(head1 = c(1, 0, 0, 0, 1, 0, 0, 0, 0, 
    0)), .Names = "head1", row.names = c(NA, -10L), class = "data.frame")), .Names = c("df1", 
"df2"))

Upvotes: 2

Related Questions