'Is there a way to mutate a new column that combines an integer column with a character column
Here is a section of my full dataset:
PlotNumber Date
1 2011 7.13.2020
2 2021 7.13.2020
3 2031 7.13.2020
4 2011 7.14.2020
5 2021 7.14.2020
6 2031 7.14.2020
I would like to create a new column that takes the number from "PlotNumber" and adds another number to the end based on which character is in the "Date" column. Below is an example of what I would like the final dataset to look like.
PlotNumber Date Plot
1 2011 7.13.2020 20111
2 2021 7.13.2020 20211
3 2031 7.13.2020 20311
4 2011 7.14.2020 20112
5 2021 7.14.2020 20212
6 2031 7.14.2020 20312
My thought process is to use the mutate function from dplyr to do this, but I don't know how to assign an identifying number to the character in the "Date" column. I used the search function on StackOverflow but was not able to find anything to accomplish this specific task.
Any help would be greatly appreciated. Thanks in advance.
Solution 1:[1]
Here is an option - get the sequence based on 'PlotNumber' (rowid from data.table or use group_by(PlotNumber) and then use row_number())
library(dplyr)
library(stringr)
library(data.table)
df1 %>%
mutate(Plot = str_c(PlotNumber, rowid(PlotNumber)))
-output
PlotNumber Date Plot
1 2011 7.13.2020 20111
2 2021 7.13.2020 20211
3 2031 7.13.2020 20311
4 2011 7.14.2020 20112
5 2021 7.14.2020 20212
6 2031 7.14.2020 20312
Or with dplyr alone
df1 %>%
group_by(PlotNumber) %>%
mutate(Plot = str_c(PlotNumber, row_number())) %>%
ungroup
Or with base R
df1$Plot <- with(df1, paste0(PlotNumber, ave(seq_along(PlotNumber),
PlotNumber, FUN = seq_along))
data
df1 <- structure(list(PlotNumber = c(2011L, 2021L, 2031L, 2011L, 2021L,
2031L), Date = c("7.13.2020", "7.13.2020", "7.13.2020", "7.14.2020",
"7.14.2020", "7.14.2020")), class = "data.frame",
row.names = c("1",
"2", "3", "4", "5", "6"))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | akrun |
