I have the following problem. I have a column with 7 characters (1234567), and I want to always remove the last character (7) leave it with only 6 characters (123456). But also preserve all columns of the dataframe.
Could you ask this with a minimal REPRoducible EXample (reprex)? A reprex makes it much easier for others to understand your issue and figure out how to help.
To keep only the 6 first character on a character vector of 7 character length, you could do it these ways with stringr
vec <- c("123456", "abcdefg")
# select the first 6 character
stringr::str_sub(vec, start = 1, end = 6)
#> [1] "123456" "abcdef"
# or end before the last character
stringr::str_sub(vec, end = -2)
#> [1] "12345" "abcdef"
# trunc with no evecpsis
stringr::str_trunc(vec, 6, ellipsis = "")
#> [1] "123456" "abcdef"
Created on 2018-08-14 by the reprex package (v0.2.0.9000).
To only apply this transformation to one column in a data.frame (or a tibble), you can do it with mutate in dplyr
library(dplyr, warn.conflicts = FALSE)
# create a tibble with dummy col for the reprex
data_frame(vec = c("123456", "abcdefg"), other_col = c(1, 2), other_col2 = c("A", "B")) %>%
# apply a transformation only specified columns
mutate(
# apply the transformation of the vec column
vec = stringr::str_sub(vec, start = 1, end = 6)
)
#> # A tibble: 2 x 3
#> vec other_col other_col2
#> <chr> <dbl> <chr>
#> 1 123456 1 A
#> 2 abcdef 2 B
Created on 2018-08-14 by the reprex package (v0.2.0.9000).
If your question's been answered, would you mind choosing a solution? It helps other people see which questions still need help, or find solutions if they have similar problems. Here’s how to do it: