简体   繁体   English

R:如何将数据帧值缩短为第一个字符

[英]R: How to shorten data frame values to first character

I would like to shorten the values of one column of my data.frame. 我想缩短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 . 我已阅读其他建议使用gsubstri_replace_all_charclassstrsplit But I am afraid I need help to implement this. 但我担心我需要帮助来实现这一点。

你可以使用strtrim

df$col1 <- strtrim(df$col1, 1)

The stringr package is great: stringr包很棒:

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"

你需要的是子串函数:

df$col1 <- substr(df$col1, 1, 1)

I agree with Robin. 我同意罗宾的观点。 using the substr or substring function will directly do the trick without having to install any package. 使用substr或substring函数将直接执行该操作,而无需安装任何包。

df$col1 <- substr(df$col1, 1, 1)

or df$col1 <- substring(df$col1,1,1) 或者df $ col1 < - substring(df $ col1,1,1)

use syntax substr (target vector, start place, stop place) 使用语法substr(目标向量,起始位置,停止位置)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM