Hye there,
I am very new using Rstudio and i struggle using substr function. I need to Create the new variable country in taking the first two letters of the variable CITIES (Codes) using the substr function. I have a database (which is called dataset2) with this kind of variable : my first column is for CITIES (Codes) like BE001C, my second one for CITIES (Labels) like Brussels, my third one is waste 2012 (amount of waste)…
I need to create a new variable but i am struggling doing it. Could someone help me getting a better understanding of the situation.
Thanks in advance,
Rod
substr
is simple
o <- "BE001C"
e <- substr(o,1,2)
e
#> [1] "BE"
Created on 2022-11-25 by the reprex package (v2.0.1)
Here o
is an object containing a six-letter string. e
is another object created by applying substr
to o
from position 1
to position 2
.
No embedded blanks, close-up as waste2012
or waste_2012
.
Creating the variable is distinct from naming it. If you have a data frame with 5 rows and 3 columns called dat
and you want to add a column of five rows
dat$new <- c(1,2,3,4,5)
for example. Then you can rename using colnames.
library(tidyverse)
dataset2 <- tibble(cit_codes = c("BE001C", "SR567F"),
cit_labels = c("Brussels", "Example"),
waste = c(30, 40))
# A tibble: 2 × 3
cit_codes cit_labels waste
<chr> <chr> <dbl>
1 BE001C Brussels 30
2 SR567F Example 40
dataset2 <- dataset2 %>%
mutate(contry = substr(cit_codes, start = 1, stop = 2))
Result
# A tibble: 2 × 4
cit_codes cit_labels waste contry
<chr> <chr> <dbl> <chr>
1 BE001C Brussels 30 BE
2 SR567F Example 40 SR
Dear flm, dear technocrat, thanks for your answers but R says that the function mutate is unknown. Why does it do that ?
try to add at the beginning of the script this line library(tidyverse)
A big thanks to you, it works !!!!
If solved, you can close clicking solved
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.
If you have a query related to it or one of the replies, start a new topic and refer back with a link.