有没有办法在我的lapply()函数中获取列表索引名称?
n = names(mylist)
lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" })
Run Code Online (Sandbox Code Playgroud)
我之前询问是否可以在lapply()返回列表中保留索引名称,但我仍然不知道是否有一种简单的方法来获取自定义函数中的每个元素名称.我想避免在名称本身上调用lapply,我宁愿在函数参数中获取名称.
我经常使用具有"R友好"/"程序员友好"列名的数据框,通常没有空格和/或缩写(懒惰以在进行分析时键入全名).例如:
ir <- data.frame(
sp=iris$Species,
sep.len=iris$Sepal.Length,
sep.wid=iris$Sepal.Width,
pet.len=iris$Petal.Length,
pet.wid=iris$Petal.Width
)
Run Code Online (Sandbox Code Playgroud)
当我用ggplot绘制这些时,我经常想用"用户友好"的列名替换标签,例如
p <- ggplot(ir, aes(x=sep.len, y=sep.wid, col=sp)) + geom_point() +
xlab("sepal length") + ylab("sepal width") +
scale_color_discrete("species")
Run Code Online (Sandbox Code Playgroud)
问题:有没有办法指定标签映射进入ggplot?
lazy.labels <- c(
sp ='species',
sep.len='sepal length',
sep.wid='sepal width',
pet.len='petal length',
pet.wid='petal width'
)
Run Code Online (Sandbox Code Playgroud)
并做一些类似的事情
p + labs(lazy.labels)
Run Code Online (Sandbox Code Playgroud)
甚至
p + xlab(lazy.labels[..x..]) + ylab(lazy.labels[..y..])
Run Code Online (Sandbox Code Playgroud)
在哪里..x..,..y..是一些自动ggplot变量保存当前X/Y变量的名称?(然后我可以将这些注释放入一个便利函数中而不必为每个图更改它们)
当我在报告中制作许多图时,这尤其有用.我总是可以ir使用"用户友好"列重命名,但之后我必须做很多事情
ggplot(ir, aes(x=`sepal length`, y=`sepal width`, ...
Run Code Online (Sandbox Code Playgroud)
由于所有的空间,这有点麻烦.