Reputation:
I am a new user of R, I am using an apply function to count the similar variables in columns. I want to first count the similar variables in the first column, but then instead of just counting the similar variables in the second column I want to count the first and second columns. And then subsequently adding an additional column.
apply(df, 2, function(x){ x1 <- count(na.omit(x))})
My data looks like this.
df <- data.frame(x = c('a', 'b', 'b'), y = c(NA, 'b','c'), z = c(NA, NA, 'a'))
I want this output :
|x|count|
a | 1
b | 2
|x|y|count|
b | b | 1
b | c | 1
|x|y|z|count
b | c |a | 1
Any help is really appreciated.
Upvotes: 0
Views: 41
Reputation: 39174
We can consider using the dplyr
package to achieve this task.
library(dplyr)
lapply(1:ncol(df), function(i){
df2 <- df %>%
select(1:i) %>%
na.omit() %>%
group_by_all() %>%
tally() %>%
ungroup()
return(df2)
})
# [[1]]
# # A tibble: 2 x 2
# x n
# <fct> <int>
# 1 a 1
# 2 b 2
#
# [[2]]
# # A tibble: 2 x 3
# x y n
# <fct> <fct> <int>
# 1 b b 1
# 2 b c 1
#
# [[3]]
# # A tibble: 1 x 4
# x y z n
# <fct> <fct> <fct> <int>
# 1 b c a 1
Upvotes: 1
Reputation: 25223
You can use indexing to access the columns and then table
to get a Frequency table as follows:
lapply(seq_len(ncol(df)),
function(i) {
#take only complete cases, i.e. discard those rows with any NAs in columns
x <- df[complete.cases(df[, seq_len(i)]), seq_len(i)]
#use table to get frequency count
as.data.frame(table(x))
})
output:
[[1]]
x Freq
1 a 1
2 b 2
[[2]]
x y Freq
1 b b 1
2 b c 1
[[3]]
x y z Freq
1 b c a 1
Upvotes: 1