I am reading Wickham's Advanced R book. This question is relating to solving Question 5 in chapter 12 - Functionals. The exercise asks us to:
Implement a version of
lapply()
that supplies FUN with both the name and value of each component.
Now, when I run below code, I get expected answer for one column.
c(class(iris[1]),names(iris[1]))
Output is:
"data.frame" "Sepal.Length"
Building upon above code, here's what I did:
lapply(iris,function(x){c(class(x),names(x))})
However, I only get the output from class(x)
and not from names(x)
. Why is this the case?
I also tried paste()
to see whether it works.
lapply(iris,function(x){paste(class(x),names(x),sep = " ")})
I only get class(x)
in the output. I don't see names(x)
being returned.
Why is this the case? Also, how do I fix it?
Can someone please help me?
Instead of going over the data frame directly you could switch things around and have lapply go over a vector of the column names,
data(iris)
lapply(colnames(iris), function(x) c(class(iris[[x]]), x))
or over an index for the columns, referencing the data frame.
lapply(1:ncol(iris), function(x) c(class(iris[[x]]), names(iris[x])))
Notice the use of both single and double square brackets.
iris[[n]]
references the values of the n
th object in the list iris
(a data frame is just a particular kind of list), stripping all attributes, making something like mean(iris[[1]])
possible.
iris[n]
references the n
th object itself, all attributes intact, making something like names(iris[1])
possible.