I would like to shorten the values of one column of my data.frame. Right now, each value consists of many letters, such as
df$col1
[1] AHG ALK OPH BCZ LKH QRQ AAA VYY
what I need is only the first letter:
df$col1
[1] A A O B L Q A V
I have read other entries that suggested to use gsub
, stri_replace_all_charclass
, or strsplit
. But I am afraid I need help to implement this.
trunc(x) is a truncate function in R, which rounds to the nearest integer in the direction of 0. trunc() function basically truncates the values in the decimal places. trunc() function is used in truncating the values of vector and truncating the values of a column in R. Lets see an example for each.
Data Visualization using R Programming To remove first character from column name in R data frame, we can use str_sub function of stringr package.
To remove a character in an R data frame column, we can use gsub function which will replace the character with blank. For example, if we have a data frame called df that contains a character column say x which has a character ID in each value then it can be removed by using the command gsub("ID","",as.
Removing the first character To remove the string's first character, we can use the built-in substring() function in R. The substring() function accepts 3 arguments, the first one is a string, the second is start position, third is end position.
You can use strtrim
df$col1 <- strtrim(df$col1, 1)
The stringr package is great:
require(stringr)
df <- data.frame(col1 = c("AHG", "ALK", "OPH", "BCZ", "LKH", "QRQ", "AAA", "VYY"))
str_sub(df$col1, 1, 1)
[1] "A" "A" "O" "B" "L" "Q" "A" "V"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With