user11916948
user11916948

Reputation: 954

Based on a vector make a function and find values in a data frame

I want to make a function which results in a list of how many times each character occur in a data frame. First I have made a data frame with values between 0-5, then I have extracted the unique values in a vector. Then one by one of this vector I want to go through how many times the characters occur in the data frame. Finally I want a table of how many times 0-5 occur. Im new in making functions and I would need some help, thanks in advance!

data <- data.frame(replicate(5,sample(0:5,10,rep=TRUE)))
df <- as.vector(as.matrix(data))
df <- unique(df)
df

libary(dplyr)
library(stringr)

test <- function(i){
  for(i in seq_along(df)) {
    data.F <- data %>% as.character() %>%
      str_count(pattern="[i]")
  }
  return(data.F)
}
df(1)  

Upvotes: 1

Views: 59

Answers (2)

akrun
akrun

Reputation: 887213

Regarding the OP's function, the str_count is vectorized, so we don't need to loop. In addition, if we are creating a pattern, use paste or str_c to interpolate the 'i', i.e. str_c("[", i, "]"). Based on the OP's code, it seems that the OP was counting the characters in each of the string

library(stringr)
str_count(df, "1")
#[1] 1 0 0 0 0 0 1 0 2 1 0 1 0 1 0 0 0 1 0

To get counts for 0:5

library(purrr)
map(as.character(0:5), ~ str_count(df, .x))

If we are just looking for the count use

library(dplyr)
tibble(col = df) %>% 
         count(col)

Upvotes: 0

Edo
Edo

Reputation: 7818

If I understood correctly what you're looking for, you just need table. Table shows you how many times each value appears

data <- data.frame(replicate(5,sample(0:5,10,rep=TRUE)))

data

#    X1 X2 X3 X4 X5
# 1   2  5  1  3  3
# 2   0  5  4  4  2
# 3   1  2  1  1  1
# 4   3  5  4  2  5
# 5   5  1  1  5  4
# 6   2  4  0  2  0
# 7   1  4  1  1  0
# 8   1  4  1  2  0
# 9   1  0  5  0  4
# 10  4  3  0  1  1

table(as.matrix(data))

# 0  1  2  3  4  5  # <- unique values
# 8 15  7  4  9  7  # <- frequency

Upvotes: 4

Related Questions