I have the following problem.

I want to turn a string e.g

> a<-paste('x=col1,y=col2,fill=col3')

into a form that aes_string accepts like this: x='col1',y='col2',fill='col3'

this is part of a function:

>fun<-function(data,aes.string=''){
aes_mapping <- aes_string(aes.string)
p <- ggplot(df.data,mapping=aes_mapping )
p <- p + geom_point()
return(p)
}

if i call

> 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")

Any help appreciated!

有帮助吗?

解决方案

From Use character string as function argument:

However in this case you don't need aes_string since you not passing strings (no "). I also fixed a typo in 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)

enter image description here

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top