我有以下问题。
我想转一个字符串,例如
> a<-paste('x=col1,y=col2,fill=col3')
进入aes_string接受的形式:x ='col1',y ='col2',fill ='col3'
这是功能的一部分:
>fun<-function(data,aes.string=''){
aes_mapping <- aes_string(aes.string)
p <- ggplot(df.data,mapping=aes_mapping )
p <- p + geom_point()
return(p)
}
如果我打电话
> fun(df.sam,a)
> Error in parse(text = x) : <text>:1:7: unexpected ','
1: x=col1,
^
>dput(df.sam)
structure(list(col1 = c(1.99340197320543, 4.96225966782141, 1.42191486886353,
5.41389048265218, 1.48427007201488, 3.43977166739915, 2.43656907238302,
2.863856404804, 2.71825401870433, 3.17825292487285), col2 = c(76.2306398916608,
5.89150952248784, 38.634046526178, 28.3032368687166, 14.7025137552809,
9.11163890447616, 46.3416263715291, 31.9935691220763, 49.799629992835,
24.5153013442625), col3 = c(152, 600, 305, 375, 305, 300, 229,
330, 229, 300)), .Names = c("col1", "col2", "col3"), row.names = c(NA,
10L), class = "data.frame")
任何帮助表示赞赏!
答案 0 :(得分:2)
来自Use character string as function argument:
但是在这种情况下,您不需要aes_string
,因为您没有传递字符串(没有"
)。我还修复了fun()
中的拼写错误。
fun<-function(data,aes.string=''){
aes_mapping <- eval(parse(text = paste("aes(", a, ")")))
p <- ggplot(data,mapping=aes_mapping )
p <- p + geom_point()
return(p)
}
a<-paste('x=col1,y=col2,fill=col3')
fun(df.sam,a)