nouse
nouse

Reputation: 3461

Pasting names to an object during lapply

Consider this code:

df <- as.data.frame(matrix(rnorm(9),3,3))   
names(df) <- c("A","B","C")
y <- c(1,2,3)
list1 <- lapply(df, function(x) as.vector(x))
par(mfrow=c(1,3))
lapply(list1, function(x) plot(x,y))

I want to paste the name of each vector in list1 (A, B, C) to the x-axis of the respective x,y-plot. Can i do it during lappy, or is it necessary to write a loop?

Upvotes: 0

Views: 215

Answers (1)

Heroka
Heroka

Reputation: 13139

You can do it using 'lapply', while iterating over names:

lapply(names(list1),function(nn){
  plot(list1[[nn]],y,ylab=nn)
}
)

Upvotes: 1

Related Questions