Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

mixed.1 <- c(TRUE,TRUE,FALSE,4,0,3) mixed.1 ## [1] 1 1 0 4 0 3 mixed.2 <- c(c(TR

ID: 3911739 • Letter: M

Question

mixed.1 <- c(TRUE,TRUE,FALSE,4,0,3)

mixed.1

## [1] 1 1 0 4 0 3

mixed.2 <- c(c(TRUE,TRUE,FALSE,4,0),"3")

mixed.2

## [1] "1" "1" "0" "4" "0" "3"

mixed.3 <- c(TRUE,TRUE,FALSE,4,0,"3")

mixed.3

Type Casting: The as.logical(), as.numeric(), and as.character() functions allow us to coerce (or cast) a vector into one of a different mode. For example:

as.logical(c("TRUE","FALSE","TRUE"))

## [1] TRUE FALSE TRUE

as.numeric(c("4","0","3"))

## [1] 4 0 3

as.character(c(TRUE,FALSE,TRUE))

## [1] "TRUE" "FALSE" "TRUE"

(a) Explain why as.numeric(mixed.2) and as.numeric(mixed.3) produce different results.

(b) Explain why as.logical(mixed.2) and as.logical(mixed.3) produce different results.

(c) How could you use the type casting functions to coerce mixed.2 into a meaningful logical vector?

Explanation / Answer

Answer :

a) as.numeric(mixed.2) will return [1] 1 1 0 4 0 3 and as.numeric(mixed.3) will return [1] NA NA NA 4 0 3, where NA stands for not available the reason for this is that mixed.3 contains [1] "TRUE" "TRUE" "FALSE" "4" "0" "3" and when coercion has to be done with as.numeric(), the system will not be able to convert the strings "True" and "FALSE" into numeric values thus return NA for them.(in R character have higher precedence than integer thats why mixed.c contains all character entries).

b)  as.logical(mixed.2) will return :
[1] NA NA NA NA NA NA
as.logical(mixed.3) will return :
[1] TRUE TRUE FALSE NA NA NA

mixed.2 contain all the integer entries converted into the string type and precedence of integer as well as character is greater than logical, thus as.logical() will not be able to convert it to logical entries. thus return NA for all the entries.

mixed.3 contains 3 logical entries being converted to character type due to conversion to highest types while forming list, thus when we do type conversion using as.logical() these will be converted back to logical and rest entries will be NA.

c) as.numeric(mixed.2)
[1] 1 1 0 4 0 3

> as.logical(as.numeric(mixed.2))
[1] TRUE TRUE FALSE TRUE FALSE TRUE

first use as.numeric() function as the mixed.2 contain all integer entries converted into character type so they can be easily converted into numerics, later these numeric entries can be easily typecasted using as.logical() function.

Hope this helps

please upvote