I have data frame like below
Col1 Col2
White Orange
White Blue
Red White
On executing the below code,the items from both columns adds together. Please explain how the function works and how does the function know it should add row vice data instead of column.
paste_fun <- function(i){
(paste(as.character(i),collapse=" "))
}
and below code adds a new column to the data frame.My question is here 1 is entered which is row how is it considers it as a new column.
phone_data["new_col"] <- apply(phone_data(as.character[i]),1,paste_fun)
That function doesn't know anything about columns. It is being deployed via the apply
function which has a second argument determining whether to work on rows or columns. That function is given a single row of the dataframe as a vector and pastefun
puts the values together using collapse=" "
. And the [<-
-function is what put the values from the paste call in a column of a dataframe.
The paste
-function usually operates in a vectorized manner, returning a vector of length determined by the length of its arguments. The collapse
argument, however, changes how it operates and "collapses" all of the values and thus returns a length-1 character vector (one for each row when deployed via apply( ..., 1, ...}
So it's really the apply
-function that gets credit for acting row-wise on the data frame, and the [<-
function that gets credit for creating a new column.