'Assign name in column based on values from another column
I am looking for some help to what seems like a very simple question. Any advice is greatly appreciated! I have created a data frame and I am looking to assign names under one column based on the values in the other column.
`rdf<-as.data.frame(matrix(NA, nrow= 59, ncol=2))'
row names(rdf)<- c(1:35, 37:60)
colnames(rdf)<-c("Unit", "Region")
rdf$Unit<-c(1:35, 37:60)
rdf$Region<- ##Here I want for Units 1:13 <- the region to be East, for Units 14:25 and 27 the region to be labeled Central, units 26, 28:43, 45:46, and 58 to be labeled West, And then Units 44,47:57, and 59:60 to be labeled BC`
Ive been trying case_when or nested if else statements, but I am getting errors relating to a longer object length is not a multiple of shorter object length.
Solution 1:[1]
Try the following and tweak to suit your situation.
library(dplyr)
#The below 2 commands will add a rowid column to the dataframe to uniquely identify the rows
rdf<- rdf %>%
rowid_to_column() %>%
# filter(rowid !=36) # filter rows that you do not want.
#assuming csv_rdf contains column named "unit"
csv_rdf<- csv_rdf %>%
rowid_to_column() %>%
main_df<- rdf %>%
left_join(csv_df, by="rowid") # this will populate the csv$unit column to the rdf dataframe. The join will be done based on column rowid.
main_df<- main_df %>%
mutate(region = case_when(
units >=1 & unique <=13 ~ "East",
units >=14 & unique <=25 ~ "Central",
units ==27 ~ "Central", # Add all your conditions below
TRUE ~ 'TBD' # this is kind of catch-all and will need to be re-checked.
))
Solution 2:[2]
After your rdf$Unit<-c(1:35, 37:60) statement, Can you try the following?
rdf %>%
mutate(Region=case_when(
Unit >=1 & Unit <=13 ~ 'East',
Unit >=14 & Unit <=25 ~ 'Central',
Unit ==27 ~ 'Central',
Unit ==26 | Unit ==58 ~ 'West',
Unit >=28 & Unit <=43 ~ 'West',
Unit >=45 & Unit <=46 ~ 'West',
Unit ==44 ~ 'BC',
Unit >=47 & Unit <=57 ~ 'BC',
Unit >=59 & Unit <=60 ~ 'BC',
TRUE ~ "Error" # keeping this to later check if all values are populated or not.. Can do count()
))
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 | Vinay |
| Solution 2 | Vinay |
