88% found this document useful (8 votes)
6K views8 pages

R Basics

The document contains examples demonstrating various R functions for working with vectors, matrices, dates, factors, and more. Key functions demonstrated include levels(), as.Date(), sample(), is.na(), median(), which(), and str(). A variety of functions are also defined to perform operations on input vectors and return outputs.

Uploaded by

roy.scar2196
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
88% found this document useful (8 votes)
6K views8 pages

R Basics

The document contains examples demonstrating various R functions for working with vectors, matrices, dates, factors, and more. Key functions demonstrated include levels(), as.Date(), sample(), is.na(), median(), which(), and str(). A variety of functions are also defined to perform operations on input vectors and return outputs.

Uploaded by

roy.scar2196
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 8

display levels of vector variable

choice <- c("yes","no","yes","maybe")

level1 <- levels(factor(choice))

print(level1)

[1] "maybe" "no" "yes"

without levels funtion on factor of choice, it also prints contents of choice first

str1 = "25-12-2016"
date1 = as.Date(str1, "%d-%m-%Y")
print(date1)

[1] "2016-12-25"

# Enter your code here. Read input from STDIN. Print output to STDOUT
V1 <- c(1:5)
V2 <- c(10,20,30,40,50)
print(V1 + V2)

[1] 11 22 33 44 55

V <- c(1:9)
M <- matrix(V, byrow =TRUE, nrow = 3)
print (M * 2)

[,1] [,2] [,3]


[1,] 2 4 6
[2,] 8 10 12
[3,] 14 16 18

Char >num >logic

Convert factor vector to numeric type without carrying out the cardinal level value
mistake in v2 <- as.numeric(v1)

v1 <- factor (round(runif(10,10,70)))

v2 <- as.numeric(as.character(v1))
v1 == v2

[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE

random_function <- function(length,start,end,precision) {

# Enter your code here.


V <- round(runif(length,start,end),precision)
return (V)

}#End Function
print(length(random_function(10,0.0,10.0,2)))

[1] 10

sample(U,5) no replacement by default

sample (U,) gives entire set in random order

sample(U,12, replace=TRUE ) with replacement

if U has one element say 4 then sample (U,1) reads sample (c(1,2,3,4),1)

Missing value is undisclosed data say for category age represented as 'NA'

class(NA)
[1]"logical"

is.na(U) checks for NA in vector U


U[!is.na(U] # to eliminate missing values

na.omit(U) #also does the same


Remove NA and odd values form vector V passed as parameneter thru function call
handling_na <- function(V)
{

# Enter your code here. Read input from STDIN. Print output to STDOUT
V<-V[!(is.na(V)| V %% 2 == 1)]

return (V)
}
vec<-c(1, 4 ,NA ,7 ,9 ,NA ,2)
print(handling_na(vec))

Set Difference between 2 passed sets

set_handling <- function(A,B)


{

# Enter your code here. Read input from STDIN. Print output to STDOUT
set_handling <- function(A,B)
{

# Enter your code here. Read input from STDIN. Print output to STDOUT
C<- setdiff(A,B)

return (C)
}
print(set_handling(c(11:16),c(13:20)))

[1] 11 12
stats <- function(V)
{

Median of vector V

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<-median(V)

return (ans)
}
print(stats(c(11:17)))

[1] 14

conditional <- function(V)


{

# Enter your code here. Read input from STDIN. Print output to STDOUT

#print(unname(ifelse((V >= 80),"Above_Average","Average")),quote = FALSE, row.name


= FALSE)
cat(ifelse((V >= 80),"Above_Average","Average")) # to print without quotes and line
number [1]

conditional(c(78,85,90))

Average Above_Average Above_Average

conditional <- function(M)


{

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<-which(M > 13 & M < 16)

return(ans)
}
print(conditional( c(10:20)))
[1] 5 6

loop <- function(V) {

# Enter your code here. Read input from STDIN. Print output to STDOUT
sum1 = 0
for (i in V)
{
if (i %% 2 == 0)
{
sum1 = sum1 + i
}
}
ans<-sum1
return (ans)
}
print(loop(c(80:100)))

Cube <- function(num) {

return(num**3)
}
print(Cube(10))
print(Cube(3))
print(Cube(4))
print(Cube(5))

[1] 1000
[1] 27
[1] 64
[1] 125

leap<-function(D){

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<- format(D, "%Y")

return (ans)
}
print(leap(as.Date('2018-01-01')))
print(leap(as.Date('2022-01-01')))

[1] "2018"
[1] "2022"

operation<-function(L1,L2){

# Enter your code here. Read input from STDIN. Print output to STDOUT for (root L1
x L2)
ans<-((L1 ** 0.5) * L2)

return (ans)
}
print(operation(4,2))
print(operation(100,4))

[1] 4
[1] 40

convert<-function(K){

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<- ifelse(is.integer(K),K,as.integer(K))

return (ans)
}
print(convert(2.7))
print(convert(3.456))
print(convert(4.1))

[1] 2
[1] 3
[1] 4

level<-function(V){

# Enter your code here. Read input from STDIN. Print output to STDOUT (return
number of levels) use nlevel
ans<-nlevels(factor(V))

return(ans)
}
print(level(c("Red","Green","Blue")))
print(level(c("Single","Married")))
print(level(c("Apple","Apple","Orange","Mango")))

[1] 3
[1] 2
[1] 3

sequence_gen<-function(a,b){

# Enter your code here. Read input from STDIN. Print output to STDOUT even digits
of sequence a:b repeated twice
ans<-rep(subset(c(a:b), c(a:b) %% 2 == 0 ), times = 2)

return(ans)
}
print(sequence_gen(10,20))
print(sequence_gen(28,45))

[1] 10 12 14 16 18 20 10 12 14 16 18 20
[1] 28 30 32 34 36 38 40 42 44 28 30 32 34 36 38 40 42 44

multi<-function(a,b,c,d){

# Enter your code here. Read input from STDIN. Print output to STDOUT
X <- c(a:b)
Y <- c(c:d)
ans<- X * Y

return(ans)
}
print(multi(1,3,4,6))
print(multi(10,16,24,30))

[1] 4 10 18
[1] 240 275 312 351 392 435 480
create_mat<-function(V,r,c){

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<- matrix(V,nrow = r,ncol = c)

return(ans)
}
print(create_mat(c(2,4,6,8,0,9),2,3))

print(create_mat(c(12,14),1,2))

print(create_mat(c(15),1,1))

[,1] [,2] [,3]


[1,] 2 6 0
[2,] 4 8 9
[,1] [,2]
[1,] 12 14
[,1]
[1,] 15

convert_date<-function(S){

# Enter your code here. Read input from STDIN. Print output to STDOUT

ans<- format(as.Date(S, "%d%m%Y"), "%Y-%m-%d")

return(ans)
}

print(convert_date("15081947"))
print(convert_date("18081995"))
print(convert_date("04021967"))
print(convert_date("06091969"))

[1] "1947-08-15"
[1] "1995-08-18"
[1] "1967-02-04"
[1] "1969-09-06"

elapsed_days<-function(X,Y){

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<-as.POSIXct(as.Date(X,"%d%B%Y")) - as.POSIXct(as.Date(Y,"%d%B%Y"))

return (ans)
}
print(elapsed_days("15Jan2020","12Dec1983"))
print(elapsed_days("18Aug2021","18Aug1995"))

Time difference of 13183 days


Time difference of 9497 days

condition<-function(temp){

# Enter your code here. Read input from STDIN. Print output to STDOUT
V<- ifelse(temp > 100, "Hot", "Normal")

return(V)
}
print(condition(c(102,98,67,115)))
print(condition(c(89,125)))
print(condition(c(99,45,56)))

[1] "Hot" "Normal" "Normal" "Hot"


[1] "Normal" "Hot"
[1] "Normal" "Normal" "Normal"

classmark<-function(marks){

# Enter your code here. Read input from STDIN. Print output to STDOUT
ans<- ifelse(all(marks > 90), "Best Class", "Needs Improvement")

return(ans)
}
print(classmark(c(100,95,94,56)))
print(classmark(c(100,95,94,96)))

[1] "Needs Improvement"


[1] "Best Class"

# Enter your code here. Read input from STDIN. Print output to STDOUT
Nfact <- function(num){
fact = 1
i = 1

while (i <= num)


{
fact = fact * i
i = i + 1
}

return (fact)
}
print(Nfact(6))
print(Nfact(5))
print(Nfact(9))

[1] 720
[1] 120
[1] 362880

# Enter your code here. Read input from STDIN. Print output to STDO
sum_whole <- function(N){
ans = 0
i = 1
while (i <= N){
ans = ans + i
i = i + 1
}
return(ans)
}
print(sum_whole(20))
print(sum_whole(32))
print(sum_whole(4))

[1] 210
[1] 528
[1] 10

find_matches<-function(scores){

# Enter your code here. Read input from STDIN. Print output to STDOUT for matches
with even score
ans<- which(scores %% 2 == 0)

return(ans)
}
print(find_matches(c(102,34,56,77)))
print(find_matches(c(100,90,21)))

[1] 1 2 3
[1] 1 2

inspect<-function(names,details){
df <- data.frame(names,details)
str(df)
# Enter your code here. Read input from STDIN. Print output to STDOUT
}
inspect(c("Ajay","Ajith","Akhila"),c("Manager","Trainee","Trainee"))

'data.frame': 3 obs. of 2 variables:


$ names : Factor w/ 3 levels "Ajay","Ajith",..: 1 2 3
$ details: Factor w/ 2 levels "Manager","Trainee": 1 2 2

# Enter your code here. Read input from STDIN. Print output to STDOUT
pyth <- function(a,b){
c = ((a ** 2) + (b ** 2)) ** 0.5
return(c)
}

print(pyth(3,4))
print(pyth(6,8))

[1] 5
[1] 10

You might also like