如何将双引号插入传递给粘贴函数的字符串向量?

时间:2015-07-09 14:19:04

标签: r string-split

我有一个data.frames循环,我希望将它们转换为长格式。我有一些存储在向量中的字符串,我打算将它们作为id.vars语句传递给melt()

以下是四个data.frames,转载

df1<-structure(list(Year = 2012L, Area = "South", TopSumOfCount = 780L), .Names = c("Year", 
"Area", "TopSumOfCount"), row.names = c(NA, -1L), class = "data.frame")

df2<-structure(list(Year = 2012L, Category = "Condiments", TopSumOfCount = 780L), .Names = c("Year", 
"Category", "TopSumOfCount"), row.names = c(NA, -1L), class = "data.frame")

df3<-structure(list(Year = 2012L, Area = "South", TopSumOfCount = 780L), .Names = c("Year", 
"Area", "TopSumOfCount"), row.names = c(NA, -1L), class = "data.frame")

df4<-structure(list(Year = 2012L, Category = "Condiments", TopSumOfCount = 780L), .Names = c("Year", 
"Category", "TopSumOfCount"), row.names = c(NA, -1L), class = "data.frame")

AllDF_Names<-c("df1","df2","df3","df4")

要以长格式呈现它,我需要使用melt(),我遇到了使用组合函数的需要。要使用的id.vars存储在向量中,我希望保留它那样!

所以,我使用这个dQuote尝试在分割字符串“Year,Area”之后插入一个双引号,并尝试获取一个字符串,如“c(\”Year \“,\”Area \ “)”

ParticipantsForMelt<-c("Year,Area", "Year,Category", "Year,Area", "Year,Category")
 for(i in 1:length(AllDF_Names){


 MeltStatement[i]<-paste0(AllDF_Names[i],"_long<-melt(",
               AllDF_Names[i],",","id.vars=",
               dQuote(strsplit(ParticipantsForMelt[i],",")),")")
 eval(parse(text=MeltStatement[i]))
}

上面代码中的问题是我在一个不寻常的位置得到双引号:(注意结果中c(...)之前的双引号)

df1_long<-melt(df1,id.vars=“c(\"Year\", \"Area\")”)

期望的输出:

df1_long<-melt(df1,id.vars=c(\"Year\", \"Area\"))

1 个答案:

答案 0 :(得分:0)

这样做的一种方法是编写一个小函数,然后应用gsub:

addDoubleQuotes <- function(...)as.character(sys.call())[-1]

b=addDoubleQuotes(c("Year,Area", "Year,Category", "Year,Area", "Year,Category"))

> b
[1] "c(\"Year,Area\", \"Year,Category\", \"Year,Area\", \"Year,Category\")"

> gsub(",", '", "',b)

[1] "c(\"Year\", \"Area\"\", \" \"Year\", \"Category\"\", \" \"Year\", \"Area\"\", \" \"Year\", \"Category\")"