简体   繁体   中英

R how to select the value from a date and create a new column

For a biology master project I have a dataset will the number of dead animals per day per specie. Here is a similar dataset:

a <- c("Date", "Specie", "Number of dead animals")
b <- c("2020-01-01", "Dog", "3")
c <- c("2020-01-02", "Dog", "4")
d <- c("2020-01-03", "Dog", "5")
e <- c("2020-01-01", "Cat", "6")
f <- c("2020-01-02", "Cat", "3")
new_df <- data.frame(a, b, c, d, e, f)
View(new_df)

First, I want to get rid-off the a;b;c;d;e;f, that is the dataset should look like

Date / Specie / Number 
2020-01-01/Dog/3 
etc. 

Then, I want to create a new variable (mutate) that takes, for all species the number of dead animal at the date of 2020-01-02. That is, I want R to 1° select the value of dead animal the 2nd January for all species - 2° create a new column that has this value

I only could do it by creating a new dataset and subsetting at the date of 2020-01-02 but I'm sure sth much easier is possible. How??

Thank's in advance!

For completeness, once I have this value, I must sort them by quantile. This code works but creates a new dataset. I want to perform this with the same dataset.

dataset_02 <- subset(new_df, date == "2020-01-02")
dataset_02 <- within(dataset_02, quantile <- as.integer(cut(Dead02, quantile(Dead02, probs=0:5/5), include.lowest=TRUE)))

First, bind rows with rbind and add names with names . Then, group_by Specie and assign the value of Number of dead animals when Date == "2020-01-02" .

df <- as.data.frame(rbind(b, c, d, e, f))
names(df) <- a

library(dplyr)
df %>% 
  group_by(Specie) %>% 
  mutate(Dead02 = `Number of dead animals`[Date == "2020-01-02"])

output

  Date       Specie `Number of dead animals` Dead02
  <chr>      <chr>  <chr>                    <chr> 
1 2020-01-01 Dog    3                        4     
2 2020-01-02 Dog    4                        4     
3 2020-01-03 Dog    5                        4     
4 2020-01-01 Cat    6                        3     
5 2020-01-02 Cat    3                        3     

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM