简体   繁体   English

R 中 data.frame 列的最后一个字符

[英]Last characters of a column of a data.frame in R

I have a table inside a data.frame, and I need to get only the last two characters from that table, how do I do this?我在 data.frame 中有一个表,我只需要从该表中获取最后两个字符,我该怎么做?

Note: I was trying to do it using str_sub, but in it I can only define which character starts and which ends, and my data varies the size of characters.注意:我试图使用 str_sub 来实现,但在其中我只能定义哪个字符开始和哪个结束,并且我的数据会改变字符的大小。 Follow my example below that does not solve:请按照下面的示例进行操作,但无法解决:

base$estado <- str_sub(psd_base$itbc_name, start = 2)

You can use the functions substr() and nchar() to select the last letter of a character.您可以使用函数substr()nchar()来 select 字符的最后一个字母。 Both are directly applicable to vectors, so you can write:两者都直接适用于向量,因此您可以编写:

names = c("Alpha","Bip","Charlemagne","Haggs","O")
substr(names,nchar(names),nchar(names))

Which will give the output:这将给出 output:

[1] "a" "p" "e" "s" "O"

Since I do not have a reproducible example of your data, this example has to suffice.由于我没有您的数据的可重现示例,因此这个示例就足够了。 I think you get the idea.我想你应该已经明白了。

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

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