All Questions

2005
votes
23answers
171284 views

How to make a great R reproducible example?

When discussing performance with colleagues, teaching, sending a bug report or searching for guidance on mailing lists and here on SO, a reproducible example is often asked and always helpful. What a...
783
votes
12answers
575360 views

How to join (merge) data frames (inner, outer, left, right)?

Given two data frames: df1 = data.frame(CustomerId = c(1:6), Product = c(rep("Toaster", 3), rep("Radio", 3))) df2 = data.frame(CustomerId = c(2, 4, 6), State = c(rep("Alabama", 2), rep("Ohio", 1))) ...
128
votes
7answers
67928 views

How to reshape data from long to wide format?

I'm having trouble rearranging the following data frame: set.seed(45) dat1 <- data.frame( name = rep(c("firstName", "secondName"), each=4), numbers = rep(1:4, 2), value = rnorm(8) ...
175
votes
3answers
21213 views

Why are these numbers not equal?

The following code is obviously wrong. What's the problem? i <- 0.1 i <- i + 0.05 i ## [1] 0.15 if(i==0.15) cat("i equals 0.15") else cat("i does not equal 0.15") ## i does not equal 0.15
816
votes
9answers
317000 views

Grouping functions (tapply, by, aggregate) and the *apply family

Whenever I want to do something "map"py in R, I usually try to use a function in the apply family. However, I've never quite understood the differences between them -- how {sapply, lapply, etc.} app...
90
votes
6answers
89043 views

How do I make a list of data frames?

How do I make a list of data frames and how do I access each of those data frames from the list? I can't find a simple example of this anywhere. SO is telling me my post is too short, so I'll get th...
174
votes
9answers
214534 views

How to sum a variable by group?

Let's say I have two columns of data. The first contains categories such as "First", "Second", "Third", etc. The second has numbers which represent the number of times I saw "First". For example: Ca...
65
votes
4answers
40269 views

Reshaping data.frame from wide to long format

I have some trouble to convert my data.frame from a wide table to a long table. At the moment it looks like this: wide <- read.table(textConnection( "Code Country 1950 1951 1952 19...
383
votes
5answers
471031 views

How to convert a factor to an integer\numeric without a loss of information?

When I convert a factor to a numeric or integer, I get the underlying level codes, not the values as numbers. f <- factor(sample(runif(5), 20, replace = TRUE)) ## [1] 0.0248644019011408 0.0248644...
972
votes
15answers
919845 views

How to sort a dataframe by column(s)?

I want to sort a data.frame by multiple columns. For example, with the data.frame below I would like to sort by column z (descending) then by column b (ascending): dd <- data.frame(b = factor(c("...

Previous Next