user5433002
user5433002

Reputation:

how this function inside 'sapply' do computation?

Can you help me explain what is sapply doing here ?

mylist<-list(v1=c('Group1','Group2','Group3'))

sapply( mylist , function(x) paste( head(x,-1) , tail(x,-1) , sep = " ") )

simple 'paste' will produce following result

paste(mylist)

output: [1] "c(\"Group1\", \"Group2\", \"Group3\")"

following is what i get when i use want to see head of 'mylist' using paste. class of this is a 'character'

paste(head(mylist))
[1] "c(\"Group1\", \"Group2\", \"Group3\")"


paste(head(mylist,-1))
character(0)

paste(tail(mylist,-1))
character(0)

paste(head(mylist,-1),tail(mylist,-1))
character(0)

paste(head(mylist,-1),tail(mylist,-1),sep=' ')
character(0)

now if i use the above command inside a function along with 'sapply' i get completely different result. I just want to know what is actually happening here.

sapply( mylist , function(x) paste( head(x,-1) , tail(x,-1) , sep = " ") )
v1             
[1,] "Group1 Group2"
[2,] "Group2 Group3"

as from my knowledge i know that when i use function inside 'sapply' it perform computation over every element of a vector. please tell me how computation is going on .

Upvotes: 0

Views: 198

Answers (1)

Tensibai
Tensibai

Reputation: 15784

As you don't seem to wish to try @akrun advices, here the details for you:

> mylist<-list(v1=c('Group1','Group2','Group3'))
> str(mylist)
List of 1
 $ v1: chr [1:3] "Group1" "Group2" "Group3"
> mylist
$v1
[1] "Group1" "Group2" "Group3"

> mylist[['v1']]
[1] "Group1" "Group2" "Group3"

What sapply does is to iterate over the elements of its first parameter, so in your case x become mylist[[1]] (and there will be only one iteration as mylist is a 1 element list, this element in turn is a 3 element vector.

I.e:

sapply( mylist , function(x) paste( head(x,-1) , tail(x,-1) , sep = " ") )

Is strictly equivalent to:

x <- mylist[[1]]; paste( head(x,-1) , tail(x,-1) , sep = " ") 

As you have only one element in your list.

Upvotes: 1

Related Questions