Home > Mobile >  Determine based on the length if the sentence is odd or even and display if it is odd or pair in R
Determine based on the length if the sentence is odd or even and display if it is odd or pair in R

Time:10-21

Given a string vector containing the following: ("The house is yellow", "The car is new", "The apples are expensive") determine based on the length if the sentence is odd or even and display if it is odd or pair. He first started with a code to list the number of lines in each sentence. But I have no idea how to get the results to be expected between odd and even.

str_length(c("The house is yellow","The car is new", "The apples are expensive"))

CodePudding user response:

Use nchar to count number of characters, %% to get remainder after dividing by 2, if you get the remainder as 0 it is "even" or else "odd".

sentence <- c("The house is yellow","The car is new", "The apples are expensive")
ifelse(nchar(sentence) %% 2 == 0, 'even', 'odd')
#[1] "odd"  "even" "even"

You can break down the above steps to better understand the answer.

nchar(sentence)
#[1] 19 14 24

nchar(sentence) %% 2
#[1] 1 0 0

nchar(sentence) %% 2 == 0
#[1] FALSE  TRUE  TRUE
  •  Tags:  
  • r
  • Related