Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R:使用geom_行访问函数中的列名_R_Ggplot2 - Fatal编程技术网

R:使用geom_行访问函数中的列名

R:使用geom_行访问函数中的列名,r,ggplot2,R,Ggplot2,我有以下使用lappy生成的绘图列表。在函数subset和aes\u string中,我似乎没有问题传递对象I(列名): 不幸的是,xintercept在aes中不起作用,因此对象实际上不存在于geom\u vline的环境中 您可以将其用作快速修复: cols <- colnames(mtcars) lapply(cols[2:length(cols)], function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));

我有以下使用
lappy
生成的绘图列表。在函数
subset
aes\u string
中,我似乎没有问题传递对象
I
(列名):


不幸的是,
xintercept
aes
中不起作用,因此对象实际上不存在于
geom\u vline
的环境中

您可以将其用作快速修复:

cols <- colnames(mtcars)
lapply(cols[2:length(cols)], 
       function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
           ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
               geom_histogram()  +
                       geom_vline(xintercept=Mean,
                                  color="red", linetype="dashed", size=1)

       }
)
cols 0),aes_字符串(x=i))+
geom_直方图()+
几何线(xintercept=平均值,
color=“red”,linetype=“虚线”,大小=1)
}
)

您可以使用
aes\u字符串
,就像您在
x
中所做的一样

lapply(cols[2:length(cols)], function(i) {
    ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
        geom_histogram() +
        geom_vline(
            aes_string(xintercept = paste0("mean(", i, ", na.rm = TRUE)")),
            color = "red", linetype="dashed", size = 1)
})

+1是一个很好的解决方案。我只想补充一点,这里的文档中有一些有趣的东西。虽然
xintercept
未被列在
geom\u vline
的美学“理解”项下,但如果您将其放入
aes
(事实上,
example(geom\u vline)
中提供的一个示例使用它),它确实有效。
cols <- colnames(mtcars)
lapply(cols[2:length(cols)], 
       function(i) { Mean = with(mtcars, mean(get(i), na.rm=T));
           ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
               geom_histogram()  +
                       geom_vline(xintercept=Mean,
                                  color="red", linetype="dashed", size=1)

       }
)
lapply(cols[2:length(cols)], function(i) {
    ggplot(subset(mtcars, get(i)>0), aes_string(x=i)) +
        geom_histogram() +
        geom_vline(
            aes_string(xintercept = paste0("mean(", i, ", na.rm = TRUE)")),
            color = "red", linetype="dashed", size = 1)
})