Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
547 views
in Technique[技术] by (71.8m points)

r - How to use a character vector of column names in the formula argument of dcast (reshape2)

Say I have a dataframe df with dozens of identifying variables (in columns) and only a few measured variables (also in columns).

To avoid repetitively typing all the variables for each argument, I assign the names of the identifying and measured df columns to df_id and df_measured, respectively. It's easy enough to input these vectors to shorten the argument inputs for melt...

df.m  <- melt(df, id.vars = df_id, measure.vars = df_measured)

... but I'm at a loss for how to enter the formula = argument in dcast using the same method to specify my id variables since it requires that the input point to numeric positions of the columns.

Do I have to make a vector of numeric positions similar to df_id and risk broken functionality of my program if my input columns change in order, or can I refer to them by name and somehow still get that to work in the formula = argument? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use as.formula to construct a formula.

Here's an example:

library(reshape2)
## Example from `melt.data.frame`
names(airquality) <- tolower(names(airquality))
df_id <- c("month", "day")
aq <- melt(airquality, id = df_id)

## Constructing the formula
f <- as.formula(paste(paste(df_id, collapse = " + "), "~ variable"))

## Applying it....
dcast(aq, f, value.var = "value", fun.aggregate = mean)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...