我试图循环数据框和列以产生多个图.我有一个数据框列表,对于每个数据框,我想绘制对几个预测变量之一的响应.
例如,我可以轻松地循环数据框:
df1=data.frame(response=rpois(10,1),value1=rpois(10,1),value2=rpois(10,1))
df2=data.frame(response=rpois(10,1),value1=rpois(10,1),value2=rpois(10,1))
#Looping across data frames
lapply(list(df1,df2), function(i) ggplot(i,aes(y=response,x=value1))+geom_point())
Run Code Online (Sandbox Code Playgroud)
但是我在数据框中的列之间循环时遇到问题:
lapply(list("value1","value2"), function(i) ggplot(df1,aes_string(x=i,y=response))+geom_point())
Run Code Online (Sandbox Code Playgroud)
我怀疑它与我对待美学的方式有关.
最终我想串起来lapply生成数据帧和列的所有组合.
任何帮助表示赞赏!
编辑:Joran有它!在使用时必须将非列表响应放在引号中aes_string
lapply(list("value1","value2"), function(i) ggplot(df1,aes_string(x=i,y="response"))+geom_point())
Run Code Online (Sandbox Code Playgroud)
作为参考,这里是串联lapply函数以生成所有组合:
lapply(list(df1,df2), function(x)
lapply(list("value1","value2"), function(i) ggplot(x,aes_string(x=i,y="response"))+geom_point() ) )
Run Code Online (Sandbox Code Playgroud)
在里面aes_string(),所有变量都需要表示为character.在"响应"周围添加引号.
lapply(list("value1","value2"),
function(i) ggplot(df1, aes_string(x=i, y="response")) + geom_point())
Run Code Online (Sandbox Code Playgroud)