Sie sind auf Seite 1von 6

Dataframe

A Data frame is a list of vectors of equal length. Data frame in R is used for storing data tables.

Following are the characteristics of a data frame.

1. The column names should be non-empty.


2. The row names should be unique.
3. The data stored in a data frame can be of numeric, factor or character type.
4. Each column should contain same number of data items.

Create Data Frame in R:


Following variable student_df is a data frame containing two vectors subject and percentage

R code :

subject=c("English","Maths","Chemistry","Physics") # vector1 named as subject

percentage =c(80,100,85,95) # vector2 named as percentage

students_df=data.frame(subject,percentage) # Vector1 and vector2 together as dataframe

#Rename the columns of Data Frame

names(students_df)<-c("Course","Score")

#Accessing elements of Data frame in R:

nrow(students_df) # number of rows in data frame

ncol(students_df) # number of columns in data frame.

dim(students_df) # Dimension of data frame

students_df[1,2] # Access first row and second column of the data frame

students_df[,1] # Access all the elements of the first column

#The structure of the data frame in R can be seen by using str() function

str(students_df)

summary(students_df)#The statistical summary and nature of the data can be obtained by


applying summary() function.

Usage of Row bind rbind() function and column bind cbind() function to add the Row and Column to the
data frame.

Can join multiple vectors to create a data frame using the cbind() function.

Can merge two data frames using rbind() function.

#add an column
attempt <- c ("1st","1st","2nd","1st")
student_table<-cbind(student_df, attempt)
print(student_table)

Now make use of rbind function to insert two more rows .

Apply Function in R – apply vs lapply vs sapply vs mapply vs tapply vs


rapply vs vapply

The Apply family comprises: apply, lapply , sapply, vapply, mapply, rapply, and tapply. The Family of
Apply functions pertains to the R base package, and is populated with functions to manipulate slices of
data from matrices, arrays, lists and data frames in a repetitive way. Apply Function in R are designed to
avoid explicit use of loop constructs. They act on an input list, matrix or array, and apply a named
function with one or several optional argument.

An apply function could be:

a) an aggregating function, like for example the mean, or the sum (that return a number or scalar);
b) other transforming or sub-setting functions;
c) and other vectorized functions, which return more complex structures like list, vectors, matrices
and arrays.
1. Apply Function in R:

Returns a vector or array or list of values obtained by applying a function to margins of an array
or matrix.

Syntax for Apply function in R:


apply(x,1,sum)
Where the first Argument X is a data frame or matrix
Second argument 1 indicated Processing along rows .if it is 2 then it indicated processing along
the column.
Third Argument is some aggregate function like sum, mean etc or some other user defined
functions.

example :

Age<-c(56,34,67,33,25,28)
Weight<-c(78,67,56,44,56,89)
Height<-c(165, 171,167,167,166,181)
BMI_df<-data.frame(Age,Weight,Height)
BMI_df
apply(BMI_df,1,sum)

apply(BMI_df,2,sum)

lapply function in R:
lapply function takes list, vector or Data frame as input and returns only list as output.

lapply(BMI_df, mean)

#lapply(BMI_df, function(BMI_df) BMI_df/2)

sapply function in R
sapply function takes list, vector or Data frame as input. It is similar to lapply function but
returns only vector as output.
sapply(BMI_df, mean)# applies mean function to the columns of the dataframe and the output
will be in the form of vector

mapply function in R:
mapply is a multivariate version of sapply. mapply applies FUN to the first elements of each (…)
argument, the second elements, the third elements, and so on.
i.e. For when you have several data structures (e.g. vectors, lists) and you want to apply a
function to the 1st elements of each, and then the 2nd elements of each, etc., coercing the
result to a vector/array as in sapply
mapply(sum, 1:4, 1:4, 1:4) #mapply sums up all the first elements(1+1+1) ,sums up all the second
elements(2+2+2) and so on so the result will be

rapply function in R:
rapply function in R is nothing but recursive apply, as the name suggests it is used to apply a
function to all elements of a list recursively.3
# rapply function in R
x=list(1,2,3,4)
rapply(x,function(x){x^2},class=c("numeric"))

 first argument in the rapply function is the list, here it is x.


 the second argument is the function that needs to be applied over the list.
 last argument gives the classes to which the function should be applied
To understand the power of rapply function lets create a list that contains few Sublists
# rapply function in R
x=list(3,list(4,5),6,list(7,list(8,9)))
str(x)
rapply(x,function(x) x^2,class=c("numeric"))
output: 9 16 25 36 49 64 81

vapply function in R:
vapply function in R is similar to sapply, but has a pre-specified type of return value, so it can be safer
(and sometimes faster) to use.

# vapply function in R

vapply(1:5, sqrt, 1i)

output: 1.000000+0i 1.414214+0i 1.732051+0i 2.000000+0i 2.236068+0i

paste (),paste0() function:


Paste function in R is used to concatenate Vectors by converting them into character. paste0 function in
R simply concatenates the vector with space separator.

Syntax for Paste Function in R


paste (…, sep = ” “, collapse = NULL)

Arguments
one or more R objects, to be concatenated

together.

Sep a character string to separate the terms.

an optional character string to separate the


collapse
results.
Examples
Eg 1:

paste('one',2,'three',4,'five')

output: “one 2 three 4 five”

When multiple arguments are passed to paste, it will vectorize the operation, recycling shorter elements
when necessary. This makes it easy to generate variable names with a common prefix

To find factor of a given number


# take input from the user
num = as.integer(readline(prompt="Enter a number: "))
factorial = 1
# check is the number is negative, positive or zero
if(num < 0) {
print("Sorry, factorial does not exist for negative numbers")
} else if(num == 0) {
print("The factorial of 0 is 1")
} else {
for(i in 1:num) {
factorial = factorial * i
}
print(paste("The factorial of", num ,"is",factorial))
}

Paste() function in R with Sep & collapse Argument:

The sep= argument controls what is placed between each set of values that are combined, and the
collapse= argument can be used to specify a value to use, when joining those individual values to create
a single string.

# paste function in R with sep argument

paste('X',1:5,sep='')
output: “X1” “X2” “X3” “X4” “X5”

#paste function in R with collapse argument

paste(c(1:5),collapse=' and ')

# paste function in R with separator and collapse Argument

paste(c('X','Y'),1:5,sep='_',collapse=' and ')

output: "X_1 and Y_2 and X_3 and Y_4 and X_5"

Q1: Write a R Script to count the number of even numbers in a vector.


Q2: R script to write a multiplication table.

Das könnte Ihnen auch gefallen