How paste works within a function

168 views Asked by At

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)
2

There are 2 answers

0
IRTFM On BEST ANSWER

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.

0
Tim Biegeleisen On

Given that you only have two columns in your data frame, you don't even need to use an apply function, just plain paste works:

phone_data$new_col <- paste(phone_data$Col1, phone_data$Col2)

Regarding how apply is working, you are passing 1 as the second argument, which is telling R to do the apply in row mode. So, it runs your paste function against the whole row, coerced to a character vector, to generate the concatenated result.