You can use the order()
function directly without resorting to add-on tools -- see this simpler answer which uses a trick right from the top of the example(order)
code:
R> dd[with(dd, order(-z, b)), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
Edit some 2+ years later: It was just asked how to do this by column index. The answer is to simply pass the desired sorting column(s) to the order()
function:
R> dd[order(-dd[,4], dd[,1]), ]
b x y z
4 Low C 9 2
2 Med D 3 1
1 Hi A 8 1
3 Hi A 9 1
R>
rather than using the name of the column (and with()
for easier/more direct access).
By using the merge
function and its optional parameters:
Inner join: merge(df1, df2)
will work for these examples because R automatically joins the frames by common variable names, but you would most likely want to specify merge(df1, df2, by = "CustomerId")
to make sure that you were matching on only the fields you desired. You can also use the by.x
and by.y
parameters if the matching variables have different names in the different data frames.
Outer join: merge(x = df1, y = df2, by = "CustomerId", all = TRUE)
Left outer: merge(x = df1, y = df2, by = "CustomerId", all.x = TRUE)
Right outer: merge(x = df1, y = df2, by = "CustomerId", all.y = TRUE)
Cross join: merge(x = df1, y = df2, by = NULL)
Just as with the inner join, you would probably want to explicitly pass "CustomerId" to R as the matching variable. I think it's almost always best to explicitly state the identifiers on which you want to merge; it's safer if the input data.frames change unexpectedly and easier to read later on.
You can merge on multiple columns by giving by
a vector, e.g., by = c("CustomerId", "OrderId")
.
If the column names to merge on are not the same, you can specify, e.g., by.x = "CustomerId_in_df1", by.y = "CustomerId_in_df2"
where CustomerId_in_df1
is the name of the column in the first data frame and CustomerId_in_df2
is the name of the column in the second data frame. (These can also be vectors if you need to merge on multiple columns.)
Best Answer
Basically a minimal reproducible example (MRE) should enable others to exactly reproduce your issue on their machines.
A MRE consists of the following items:
set.seed()
) for reproducibilityFor examples of good MREs, see section "Examples" at the bottom of help files on the function you are using. Simply type e.g.
help(mean)
, or short?mean
into your R console.Providing a minimal dataset
Usually, sharing huge data sets is not necessary and may rather discourage others from reading your question. Therefore, it is better to use built-in datasets or create a small "toy" example that resembles your original data, which is actually what is meant by minimal. If for some reason you really need to share your original data, you should use a method, such as
dput()
, that allows others to get an exact copy of your data.Built-in datasets
You can use one of the built-in datasets. A comprehensive list of built-in datasets can be seen with
data()
. There is a short description of every data set, and more information can be obtained, e.g. with?iris
, for the 'iris' data set that comes with R. Installed packages might contain additional datasets.Creating example data sets
Preliminary note: Sometimes you may need special formats (i.e. classes), such as factors, dates, or time series. For these, make use of functions like:
as.factor
,as.Date
,as.xts
, ... Example:where
Vectors
Matrices
Data frames
Note: Although it is widely used, better do not name your data frame
df
, becausedf()
is an R function for the density (i.e. height of the curve at pointx
) of the F distribution and you might get a clash with it.Copying original data
If you have a specific reason, or data that would be too difficult to construct an example from, you could provide a small subset of your original data, best by using
dput
.Why use
dput()
?dput
throws all information needed to exactly reproduce your data on your console. You may simply copy the output and paste it into your question.Calling
dat
(from above) produces output that still lacks information about variable classes and other features if you share it in your question. Furthermore the spaces in thetype
column make it difficult to do anything with it. Even when we set out to use the data, we won't manage to get important features of your data right.Subset your data
Tho share a subset, use
head()
,subset()
or the indicesiris[1:4, ]
. Then wrap it intodput()
to give others something that can be put in R immediately. ExampleConsole output to share in your question:
When using
dput
, you may also want to include only relevant columns, e.g. dput(mtcars[1:3, c(2, 5, 6)])Note: If your data frame has a factor with many levels, the
dput
output can be unwieldy because it will still list all the possible factor levels even if they aren't present in the the subset of your data. To solve this issue, you can use thedroplevels()
function. Notice below how species is a factor with only one level, e.g.dput(droplevels(iris[1:4, ]))
. One other caveat fordput
is that it will not work for keyeddata.table
objects or for groupedtbl_df
(classgrouped_df
) from thetidyverse
. In these cases you can convert back to a regular data frame before sharing,dput(as.data.frame(my_data))
.Producing minimal code
Combined with the minimal data (see above), your code should exactly reproduce the problem on another machine by simply copying and pasting it.
This should be the easy part but often isn't. What you should not do:
What you should do:
library()
)unlink()
)op <- par(mfrow=c(1,2)) ...some code... par(op)
)Providing necessary information
In most cases, just the R version and the operating system will suffice. When conflicts arise with packages, giving the output of
sessionInfo()
can really help. When talking about connections to other applications (be it through ODBC or anything else), one should also provide version numbers for those, and if possible, also the necessary information on the setup.If you are running R in R Studio, using
rstudioapi::versionInfo()
can help report your RStudio version.If you have a problem with a specific package, you may want to provide the package version by giving the output of
packageVersion("name of the package")
.Seed
Using
set.seed()
you may specify a seed1, i.e. the specific state, R's random number generator is fixed. This makes it possible for random functions, such assample()
,rnorm()
,runif()
and lots of others, to always return the same result, Example:1 Note: The output of
set.seed()
differs between R >3.6.0 and previous versions. Specify which R version you used for the random process, and don't be surprised if you get slightly different results when following old questions. To get the same result in such cases, you can use theRNGversion()
-function beforeset.seed()
(e.g.:RNGversion("3.5.2")
).