How to create a 2 variable barplot using ggplot2 in r - r

I have a data frame and i want to plot a bar chart with two numerical values bars side by side namely Mean_dbh and Low_AGC for each given location (SU)
How do i plot this using ggplot2
SU Mean_dbh Low_AGC
1 1 16.98921 17.696251
2 2 13.48199 8.108352
3 3 15.97746 14.584501
4 4 12.14046 28.910114
5 5 16.47509 38.047385
6 6 19.80792 31.183069
7 7 17.44469 38.192385
8 8 18.78043 12.138436
9 10 15.68889 24.195719
10 11 17.39620 26.621287
11 15 16.71296 32.219763

By using tidyverse and pivot_longer you can merge the two variables. geom_col allows to define SU as the x-axis and the value of merged variable as the y-axis. The color is defined by fill=name where name is the merged column. Axis are renamed to make things clear.
library(tidyverse)
df <- read.table(text = " SU Mean_dbh Low_AGC
1 1 16.98921 17.696251
2 2 13.48199 8.108352
3 3 15.97746 14.584501
4 4 12.14046 28.910114
5 5 16.47509 38.047385
6 6 19.80792 31.183069
7 7 17.44469 38.192385
8 8 18.78043 12.138436
9 10 15.68889 24.195719
10 11 17.39620 26.621287
11 15 16.71296 32.219763", header=T)
df
#> SU Mean_dbh Low_AGC
#> 1 1 16.98921 17.696251
#> 2 2 13.48199 8.108352
#> 3 3 15.97746 14.584501
#> 4 4 12.14046 28.910114
#> 5 5 16.47509 38.047385
#> 6 6 19.80792 31.183069
#> 7 7 17.44469 38.192385
#> 8 8 18.78043 12.138436
#> 9 10 15.68889 24.195719
#> 10 11 17.39620 26.621287
#> 11 15 16.71296 32.219763
ggplot(df %>% pivot_longer(cols = Mean_dbh:Low_AGC),
aes(x=SU, y = value, fill=name)) +geom_col(position = 'dodge') +
labs(x='Location', y='Mean_dbh or Low_AGC') +
theme(legend.title = element_blank())

Related

How can this R code be sped up with the apply (lapply, mapply ect.) functions?

I am not to proficient with the apply functions, or with R. But I know I overuse for loops which makes my code slow. How can the following code be sped up with apply functions, or in any other way?
sum_store = NULL
for (col in 1:ncol(cazy_fams)){ # for each column in cazy_fams (so for each master family eg. GH, AA ect...)
for (row in 1:nrow(cazy_fams)){ # for each row in cazy fams (so the specific family number e.g GH1 AA7 ect...)
# Isolating the row that pertains to the current cazy family being looked at for every dataframe in the list
filt_fam = lapply(family_summary, function(sample){
sample[as.character(sample$Family) %in% paste(colnames(cazy_fams[col]),cazy_fams[row,col], sep = ""),]
})
row_cat = do.call(rbind, filt_fam) # concatinating the lapply list output int a dataframe
if (nrow(row_cat) > 0){
fam_sum = aggregate(proteins ~ Family, data=row_cat, FUN=sum) # collapsing the dataframe into one row and summing the proteins count
sum_store = rbind(sum_store, fam_sum) # storing the results for that family
} else if (grepl("NA", paste(colnames(cazy_fams[col]),cazy_fams[row,col], sep = "")) == FALSE) {
Family = paste(colnames(cazy_fams[col]),cazy_fams[row,col], sep = "")
proteins = 0
sum_store = rbind(sum_store, data.frame(Family, proteins))
} else {
next
}
}
}
family_summary is just a list of 18 two column dataframes that look like this:
Family proteins
CE0 2
CE1 9
CE4 15
CE7 1
CE9 1
CE14 10
GH0 5
GH1 1
GH3 4
GH4 1
GH8 1
GH9 2
GH13 2
GH15 5
GH17 1
with different cazy families.
cazy_fams is just a dataframe with each coulms being a cazy class (eg. GH, AA ect...) and ech row being a family number, all taken from the linked website:
GH GT PL CE AA CBM
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7
8 8 8 8 8 8
9 9 9 9 9 9
10 10 10 10 10 10
11 11 11 11 11 11
12 12 12 12 12 12
13 13 13 13 13 13
14 14 14 14 14 14
15 15 15 15 15 15
The reason behind the else if (grepl("NA", paste(colnames(cazy_fams[col]),cazy_fams[row,col], sep = "")) == FALSE) statment is to deal with the fact not all classes have the same number of family so when looping over my dataframe I end up with some GHNA and AANA with NA on the end.
The output sum_store is this:
Family proteins
GH1 54
GH2 51
GH3 125
GH4 29
GH5 40
GH6 25
GH7 0
GH8 16
GH9 25
GH10 19
GH11 5
GH12 5
GH13 164
GH14 3
GH15 61
A dataframe with all listed cazy families and the total number of apperances across the family_summary list.
Please let me know if you need anything else to help answer my question.

Extracting data from dataframe using different dataframe without headers (R)

I have a gridded data as a data-frame that has daily temperatures (in K) for 30 years. I need to extract data for days that matches another data-frame and keep the first and second columns (lon and lat).
Data example:
gridded data from which I need to remove days that do not match days in the second data (df2$Dates)
>head(Daily.df)
lon lat 1991-05-01 1991-05-02 1991-05-03 1991-05-04 1991-05-05 1991-05-06 1991-05-07 1991-05-08 1991-05-09
1 5.000 60 278.2488 280.1225 280.3909 279.4138 276.6809 276.2085 276.6250 277.7930 276.9693
2 5.125 60 278.2514 280.1049 280.3789 279.4395 276.7141 276.2467 276.6571 277.8264 277.0225
3 5.250 60 278.2529 280.0871 280.3648 279.4634 276.7437 276.2849 276.6918 277.8608 277.0740
4 5.375 60 278.2537 280.0687 280.3488 279.4858 276.7691 276.3238 276.7289 277.8960 277.1232
5 5.500 60 278.2537 280.0493 280.3319 279.5066 276.7909 276.3633 276.7688 277.9313 277.1701
6 5.625 60 278.2539 280.0294 280.3143 279.5264 276.8090 276.4042 276.8111 277.9666 277.2147
1991-05-10 1991-05-11 1991-05-12 1991-05-13 1991-05-14 1991-05-15 1991-05-16 1991-05-17 1991-05-18 1991-05-19
1 276.9616 277.3436 273.3149 274.4931 274.6967 275.6298 272.2511 271.5413 271.7289 271.7964
2 276.9689 277.2988 273.3689 274.5399 274.6801 275.6307 272.2214 271.4445 271.6410 271.7023
3 276.9720 277.2533 273.4225 274.5811 274.6646 275.6241 272.1858 271.3391 271.5424 271.5989
4 276.9716 277.2080 273.4726 274.6146 274.6507 275.6109 272.1456 271.2274 271.4340 271.4872
5 276.9689 277.1632 273.5163 274.6382 274.6380 275.5917 272.1022 271.1121 271.3168 271.3693
6 276.9645 277.1190 273.5507 274.6501 274.6263 275.5672 272.0571 270.9955 271.1919 271.2469
1991-05-20 1991-05-21 1991-05-22 1991-05-23 1991-05-24 1991-05-25 1991-05-26 1991-05-27 1991-05-28 1991-05-29
1 272.2633 268.0039 268.5981 269.4139 267.7836 265.8771 263.5669 266.1666 269.7285 272.5083
2 272.2543 268.0218 268.5847 269.4107 267.7886 265.8743 263.5125 266.1031 269.6471 272.4676
3 272.2434 268.0369 268.5716 269.4089 267.7910 265.8669 263.4592 266.0332 269.5697 272.4217
4 272.2308 268.0507 268.5597 269.4090 267.7925 265.8559 263.4066 265.9581 269.4987 272.3714
5 272.2164 268.0642 268.5505 269.4112 267.7936 265.8425 263.3546 265.8797 269.4355 272.3175
6 272.2005 268.0793 268.5451 269.4154 267.7962 265.8276 263.3039 265.7997 269.3818 272.2614
1991-05-30 1991-05-31 1991-06-01 1991-06-02 1991-06-03 1991-06-04 1991-06-05 1991-06-06 1991-06-07 1991-06-08
1 274.2950 273.4715 274.5197 274.7548 273.8259 272.4433 274.1811 274.4135 274.3999 276.0327
2 274.2205 273.4638 274.5292 274.8316 273.8658 272.4700 274.1992 274.4426 274.4650 276.0698
3 274.1421 273.4549 274.5373 274.9027 273.9028 272.4980 274.2160 274.4781 274.5309 276.1012
4 274.0609 273.4452 274.5438 274.9665 273.9365 272.5273 274.2322 274.5211 274.5969 276.1255
5 273.9784 273.4353 274.5482 275.0216 273.9660 272.5576 274.2481 274.5725 274.6617 276.1417
6 273.8960 273.4253 274.5508 275.0668 273.9912 272.5887 274.2649 274.6334 274.7239 276.1487
1991-06-09 1991-06-10 1991-06-11 1991-06-12 1991-06-13 1991-06-14 1991-06-15 1991-06-16 1991-06-17 1991-06-18
1 276.5216 277.1812 277.8093 278.3013 278.5323 278.5403 277.9563 278.3461 275.8296 273.8277
2 276.5531 277.1925 277.8261 278.3409 278.4956 278.5317 277.9148 278.3234 275.8167 273.8302
3 276.5861 277.2065 277.8457 278.3748 278.4503 278.5181 277.8654 278.2939 275.8057 273.8358
4 276.6204 277.2239 277.8684 278.4029 278.3988 278.4996 277.8080 278.2583 275.7966 273.8427
5 276.6564 277.2466 277.8945 278.4253 278.3423 278.4759 277.7429 278.2171 275.7888 273.8504
6 276.6938 277.2753 277.9242 278.4414 278.2834 278.4472 277.6715 278.1714 275.7819 273.8570
1991-06-19 1991-06-20 1991-06-21 1991-06-22 1991-06-23 1991-06-24 1991-06-25 1991-06-26 1991-06-27 1991-06-28
1 275.1738 274.6805 275.6100 274.8936 273.5818 273.2099 273.1788 271.2747 273.2458 276.9931
2 275.1808 274.7123 275.7043 274.9494 273.5861 273.1770 273.2280 271.2435 273.2662 276.9822
3 275.1859 274.7478 275.7993 275.0009 273.5956 273.1439 273.2730 271.2133 273.2803 276.9678
4 275.1891 274.7879 275.8941 275.0467 273.6107 273.1106 273.3130 271.1840 273.2886 276.9502
5 275.1902 274.8337 275.9870 275.0857 273.6318 273.0777 273.3472 271.1556 273.2918 276.9307
6 275.1891 274.8864 276.0776 275.1168 273.6589 273.0454 273.3752 271.1285 273.2905 276.9101
1991-06-29 1991-06-30
1 272.0784 273.5677
2 272.0577 273.5973
3 272.0339 273.6237
4 272.0075 273.6476
5 271.9794 273.6701
6 271.9500 273.6925
Second data I'm using for extracting (using Dates variable)
>head(df2)
Dates Temp Wind.S Wind.D
1 5/1/1991 18 4 238
2 5/2/1991 18 8 93
3 5/4/1991 22 8 229
4 5/6/1991 21 4 81
5 5/7/1991 21 8 192
6 5/9/1991 17 8 32
7 5/13/1991 22 8 229
8 5/18/1991 21 4 81
9 6/2/1991 21 8 192
10 6/7/1991 17 8 32
The header of the final data I'm looking for is something like this:
>head(df3)
lon lat 1991-05-01 1991-05-02 1991-05-04 1991-05-06 1991-05-09 1991-05-13
Example data following the format of yours
Daily.df <- data.frame(lon=1:5,lat=1:5,A=1:5,B=1:5,C=1:5,D=1:5)
colnames(Daily.df) <- c("lon","lat","1991-05-01","1991-05-02","1991-05-03","1991-05-04")
lon lat 1991-05-01 1991-05-02 1991-05-03 1991-05-04
1 1 1 1 1 1 1
2 2 2 2 2 2 2
3 3 3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5
df2 <- data.frame(Dates = c("5/1/1991","5/2/1991","5/4/1991"))
Dates
1 5/1/1991
2 5/2/1991
3 5/4/1991
Using lubridate to convert df2$Dates into the right format, make a vector of the column names you want to keep (thesedates) including lon and lat. Then use select_at to keep those columns.
library(lubridate)
library(dplyr)
thesedates <- c("lon","lat",as.character(mdy(df2$Dates)))
new.df <- Daily.df %>%
select_at(vars(thesedates))
Output
lon lat 1991-05-01 1991-05-02 1991-05-04
1 1 1 1 1 1
2 2 2 2 2 2
3 3 3 3 3 3
4 4 4 4 4 4
5 5 5 5 5 5
If you want to have a long data set to match, I would think you need to first convert the dates in df2 into the proper format and then wrangle the data into wide format.
Step 1 - Convert dates into correct format
df2$Dates <- as.Date(df2$Dates, format = "%m/%d/%Y")
Step 2 - convert to wide format
library(tidyr)
spread(df2, Dates, data)

Replacing each value in a vector with its rank number for a data.frame

In this hypothetical scenario, I have performed 5 different analyses on 13 chemicals, resulting in a score assigned to each chemical within each analysis. I have created a table as follows:
---- Analysis1 Analysis2 Analysis3 Analysis4 Analysis5
Chem_1 3.524797844 4.477695034 4.524797844 4.524797844 4.096698498
Chem_2 2.827511555 3.827511555 3.248136118 3.827511555 3.234398548
Chem_3 2.682144761 3.474646298 3.017780505 3.682144761 3.236152242
Chem_4 2.134137304 2.596921333 2.95181339 2.649076603 2.472875191
Chem_5 2.367736454 3.027814219 2.743137896 3.271122346 2.796607809
Chem_6 2.293110565 2.917318708 2.724156207 3.293110565 2.530967343
Chem_7 2.475709113 3.105794018 2.708222528 3.475709113 3.088819908
Chem_8 2.013451822 2.259454085 2.683273938 2.723554966 2.400976121
Chem_9 2.345123123 3.050074893 2.682845391 3.291851228 2.700844104
Chem_10 2.327658894 2.848729452 2.580415233 3.327658894 2.881490893
Chem_11 2.411243882 2.98131398 2.554456095 3.411243882 3.109205453
Chem_12 2.340778276 2.576860244 2.549707035 3.340778276 3.236545826
Chem_13 2.394698249 2.90682524 2.542599327 3.394698249 3.12936843
I would like to create columns corresponding to each analysis which contain the rank position for each chemical. For instance, under Analysis1,Chem_1 would have value "1", Chem_2 would have value "2", Chem_3 would have value "4", Chem_7 would have value "4", Chem_11 would have value "5", and so on.
We can use dense_rank from dplyr
library(dplyr)
df %>%
mutate_each(funs(dense_rank(-.)))
In base R, we can do
df[] <- lapply(-df, rank, ties.method="min")
In data.table, we can use
library(data.table)
setDT(df)[, lapply(-.SD, frank, ties.method="dense")]
To avoid the copies from multiplying with -, as #Arun mentioned in the comments
lapply(.SD, frankv, order=-1L, ties.method="dense")
You can also do this in base R:
cbind("..." = df[,1], data.frame(do.call(cbind,
lapply(df[,-1], order, decreasing = T))))
... Analysis1 Analysis2 Analysis3 Analysis4 Analysis5
1 Chem_1 1 1 1 1 1
2 Chem_2 2 2 2 2 12
3 Chem_3 3 3 3 3 3
4 Chem_4 7 7 4 7 2
5 Chem_5 11 9 5 11 13
6 Chem_6 13 5 6 13 11
7 Chem_7 5 11 7 12 7
8 Chem_8 9 6 8 10 10
9 Chem_9 12 13 9 6 5
10 Chem_10 10 10 10 9 9
11 Chem_11 6 4 11 5 6
12 Chem_12 4 12 12 8 4
13 Chem_13 8 8 13 4 8
If I'm not mistaken, you want to have the column-wise rank of your table. Here is my solution:
m=data.matrix(df) # converts data frame to matrix, convert your data to matrix accordingly
apply(m, 2, function(c) rank(c)) # increasingly
apply(m, 2, function(c) rank(-c)) # decreasingly
However, I believe you could solve it by yourself with the help of the answers to this question
Get rank of matrix entries?

ggplot2 is plotting a line strangely

i am trying to plot the time series x_t = A + (-1)^t B
To do this i am using the following code. The problem is, that the ggplot is wrong.
require (ggplot2)
set.seed(42)
N<-2
A<-sample(1:20,N)
B<-rnorm(N)
X<-c(A+B,A-B)
dat<-sapply(1:N,function(n) X[rep(c(n,N+n),20)],simplify=FALSE)
dat<-data.frame(t=rep(1:20,N),w=rep(A,each=20),val=do.call(c,dat))
ggplot(data=dat,aes(x=t, y=val, color=factor(w)))+
geom_line()+facet_grid(w~.,scale = "free")
looking at the head of dat everything looks right:
> head(dat)
t w val
1 1 12 10.5533
2 2 12 13.4467
3 3 12 10.5533
4 4 12 13.4467
5 5 12 10.5533
6 6 12 13.4467
So the lower (blue) line should only have values 10.5533 and 13.4467. But it also takes different values. What is wrong in my code?
Thanks in advance for any help
You really should be more careful before asserting that something is "wrong". The way you are creating dat the rows are not ordered by dat$t, so head(...) is not displaying the extra values:
head(dat[order(dat$w,dat$t),],10)
# t w val
# 21 1 18 18.43530
# 61 1 18 18.36313
# 22 2 18 19.56470
# 62 2 18 17.63687
# 23 3 18 18.43530
# 63 3 18 18.36313
# 24 4 18 19.56470
# 64 4 18 17.63687
# 25 5 18 18.43530
# 65 5 18 18.36313
Note the row numbers.

Merge values of a factor column

Column data$form contains 170 unique different values, (numbers from 1 to ~800).
I would like to merge some values (e.g with a 10 radius/step).
I need to do this in order to use:
colors = rainbow(length(unique(data$form)))
In a plot and provide a better visual result.
Thank you in advance for your help.
you can use %/% to group them and mean to combine them and normalize to scale them.
# if you want specifically 20 groups:
groups <- sort(form) %/% (800/20)
x <- c(by(sort(form), groups, mean))
x <- normalize(x, TRUE) * 19 + 1
0 1 2 3 4
1.000000 1.971781 2.957476 4.103704 4.948560
5 6 7 8 9
5.950617 7.175309 7.996914 8.953086 9.952263
10 11 12 13 14
10.800705 11.901235 12.888889 13.772291 14.888889
15 16 17 18 19
15.927984 16.864198 17.918519 18.860082 20.000000
You could also use cut. If you use the argument labels=FALSE, you get an integer value:
form <- runif(170, min=1,max=800)
> cut(form, breaks=20)
[1] (518,558] (280,320] (240,280] (121,160] (757,797]
[6] (160,200] (320,359] (598,638] (80.8,121] (359,399]
[7] (121,160] (200,240] ...
20 Levels: (1.18,41] (41,80.8] (80.8,121] (121,160] (160,200] (200,240] (240,280] (280,320] (320,359] (359,399] (399,439] ... (757,797]
> cut(form, breaks=20, labels=FALSE)
[1] 14 8 7 4 20 5 9 16 3 10 4 6 5 18 18 6 2 12
[19] 2 19 13 11 13 11 14 12 17 5 ...
On a side-note, I want you to re-consider plotting with rainbow colours, as it distorts reading the data, cf. Rainbow Color Map (Still) Considered Harmful.

Resources