R变量名称和字符串的转换 发表于 2019-06-07 | 分类于 搬砖随笔 | 阅读次数: | 应用场景 数据 123456789101112data <- data.frame(x=1:5, y=3:7)data$z=sin(data$x+data$y) data$a=sin(data$x*data$y)data$b=cos(data$x+data$y)data$d=cos(data$x*data$y)data x y z a b d1 1 3 -0.7568025 0.1411200 -0.6536436 -0.98999252 2 4 -0.2794155 0.9893582 0.9601703 -0.14550003 3 5 0.9893582 0.6502878 -0.1455000 -0.75968794 4 6 -0.5440211 -0.9055784 -0.8390715 0.42417905 5 7 -0.5365729 -0.4281827 0.8438540 -0.9036922 需求:批量画散点图 123456library(ggplot2)col_names <- colnames(data)plot_list <- lapply(3:6, function(xx) { ggplot(data=data, aes(x=x, y=y, color=col_names[xx])) + geom_point() + ggtitle(col_names[xx])})cowplot::plot_grid(plotlist = plot_list, ncol = 2) 这样其实是不行的,我们将字符串传给color,color不会读取data中的数据,而是把col_names[xx]当做一个字符串来处理。 get 解决方案 1234567library(ggplot2)col_names <- colnames(data)[3:6]plot_list <- lapply(col_names, function(xx) { ggplot(data=data, aes(x=x, y=y, color=get(xx))) + geom_point() + ggtitle(xx) + theme(plot.title = element_text(hjust = 0.5))})cowplot::plot_grid(plotlist = plot_list, ncol = 2) Wrong way Correct way assignassign是get的逆运算,比如, 123assign("a", 1) # 等价于a <- 1 目前还没有遇到需要assign函数的场景,忘了它吧。 ReferenceR学习笔记(二)变量名称和字符串的转换