Unable to place string from two columns into a new one

image

library(tidyverse)

B <- tibble(x = 1:4,
       x2 = c("2", "1", "1", "block.landfill"),
       x3 = c("block.landfill", "1", "2", "tu")) %>% 
  mutate(shift1 = substr(B$x2,4,10),
         new = substr(B$x3, 4,10))

B$LANDFILL <- cbind(B$shift1,B$new)

I want to extract only the word landfill from columns x1 and x3 and place them into a new column.
I first extracted then I tried to place it in a new column but it did not work.

Hi, I've edited your post so that the code is reproducible. Please do this next time instead of a screenshot.

Below are a couple ways to get to your desired outcome. The first modifies your code by removing B$ in the substr() function (not needed because of the pipe %>%), as well as adjusting the start and end arguments to 7 and 14. The second uses the str_extract() function.

library(tidyverse)

B <- tibble(x = 1:4,
            x2 = c("2", "1", "1", "block.landfill"),
            x3 = c("block.landfill", "1", "2", "tu"))

# adjusting your example
tibble(x = 1:4,
       x2 = c("2", "1", "1", "block.landfill"),
       x3 = c("block.landfill", "1", "2", "tu")
       ) %>% 
  mutate(shift1 = substr(x2, 7, 14),
         new = substr(x3, 7, 14))
#> # A tibble: 4 × 5
#>       x x2             x3             shift1     new       
#>   <int> <chr>          <chr>          <chr>      <chr>     
#> 1     1 2              block.landfill ""         "landfill"
#> 2     2 1              1              ""         ""        
#> 3     3 1              2              ""         ""        
#> 4     4 block.landfill tu             "landfill" ""

# using the str_extract function
B %>% 
  mutate(shift1 = str_extract(x2, 'landfill'),
         new = str_extract(x3, 'landfill'))
#> # A tibble: 4 × 5
#>       x x2             x3             shift1   new     
#>   <int> <chr>          <chr>          <chr>    <chr>   
#> 1     1 2              block.landfill <NA>     landfill
#> 2     2 1              1              <NA>     <NA>    
#> 3     3 1              2              <NA>     <NA>    
#> 4     4 block.landfill tu             landfill <NA>

Created on 2023-02-05 with reprex v2.0.2.9000

1 Like

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.