简体   繁体   中英

Use apply function on subsequently more columns

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM