Home > Enterprise >  How to replicate a variable in R
How to replicate a variable in R

Time:10-17

I have a df with a column of numbers.

3
5
6
7
9
10
3
6
5
10
3
6
7

Using R, how can I create a function that will give me the numbers in the column?

I tried working off of this

is.prime <- function(n) n == 2L || all(n %% 2L:ceiling(sqrt(n)) != 0)

But not getting the result I wanted because I want the program to check the column, not provide numbers individually.

CodePudding user response:

is.prime function can be applied to each number using a for loop or any apply command so you don't need to pass the values individually.

is.prime <- function(n) n == 2L || all(n %% 2L:ceiling(sqrt(n)) != 0)
df$is_prime <- sapply(df$V1, is.prime)
df

#   V1 is_prime
#1   3     TRUE
#2   5     TRUE
#3   6    FALSE
#4   7     TRUE
#5   9    FALSE
#6  10    FALSE
#7   3     TRUE
#8   6    FALSE
#9   5     TRUE
#10 10    FALSE
#11  3     TRUE
#12  6    FALSE
#13  7     TRUE

As @Ben Bolker mentioned to get count of total prime numbers in the column you can use sum on the above output.

sum(df$is_prime)
#[1] 7
  •  Tags:  
  • r
  • Related