Reputation: 389
I have data similar to the following:
a <- list("1999"=c(1:50), "2000"=rep(35, 20), "2001"=c(100, 101, 103))
I want to make a scatterplot where the x axis is the years (1999, 2000, 2001 as given by the list names) and the y axis is the value within each list. Is there an easy way to do this? I can achieve something close to what I want with a simple boxplot(a)
, but I'd like it to be a scatterplot rather than a boxplot.
Upvotes: 1
Views: 1299
Reputation: 887148
An option using tidyr/dplyr/ggplot2
library(ggplot2)
library(tidyr)
library(dplyr)
unnest(a, year) %>%
ggplot(., aes(x=year, y=x)) +
geom_point(shape=1)
Upvotes: 0
Reputation: 44330
You could create a data frame with the year in one column and the value in the other, and then you could plot that the appropriate columns:
b <- data.frame(year=as.numeric(rep(names(a), sapply(a, length))), val=unlist(a))
plot(b)
Upvotes: 2
Reputation: 26323
This will do what you want
do.call(rbind,
lapply(names(a), function(year) data.frame(year = year, obs = a[[year]]))
)
Or break it up into two function calls (lapply
and then do.call
) to make it more understandable what's going on. It's pretty simple if you go through it. The lapply
creates one dataframe per year where each year gets all the values for that year in the list. Now you have 3 dataframes. Then do.call
binds these dataframes together.
Upvotes: 2