Anonymous function

I am reading Wickham Advanced R. This question is related to the solution to Question 5 in Chapter 12, Functionals. Exercise asks us:

Implement a version of lapply() that provides the FUN name and value of each component.

Now, when I run the code below, I get the expected response in one column.

 c(class(iris[1]),names(iris[1])) 

Output:

 "data.frame" "Sepal.Length" 

Based on the above code, here is what I did:

 lapply(iris,function(x){c(class(x),names(x))}) 

However, I only get the output of class(x) , not the names(x) . Why is this so?

I also tried paste() see if it works.

 lapply(iris,function(x){paste(class(x),names(x),sep = " ")}) 

I get class(x) only in the output. I do not see names(x) returning.

Why is this so? Also, how can I fix this?

Can anyone help me out?

+5
source share
1 answer

Instead of going through the data frame directly, you can switch things and go through the column name vector,

 data(iris) lapply(colnames(iris), function(x) c(class(iris[[x]]), x)) 

or by index for columns, referring to a data frame.

 lapply(1:ncol(iris), function(x) c(class(iris[[x]]), names(iris[x]))) 

Pay attention to the use of both single and double square brackets.
iris[[n]] refers to the values โ€‹โ€‹of the n object in the iris list (a data frame is just a special kind of list), removing all attributes, making something like mean(iris[[1]]) possible.
iris[n] refers to the nth object, all attributes are untouched, which makes something like names(iris[1]) possible.

+3
source

All Articles