Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: How to shorten data frame values to first character

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.

like image 880
PikkuKatja Avatar asked Mar 11 '15 10:03

PikkuKatja


People also ask

How do you shorten a value in R?

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.

How do you remove the first character in a column in R?

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.

How do I remove a specific character from a column in R?

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.

How do I remove the first letter in R?

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.


2 Answers

You can use strtrim

df$col1 <- strtrim(df$col1, 1)
like image 118
rmuc8 Avatar answered Nov 15 '22 09:11

rmuc8


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"
like image 33
r.bot Avatar answered Nov 15 '22 08:11

r.bot