如何使用 R 从 .xlsx 文件的列中删除最后 6 个字符?

How to delete last 6 characters from a column in .xlsx file using R?

我有一个包含 845 行和 61 列的 .xlsx 文件,其中一列是位置名称列表。但是,此列中的每个单元格都以六个不需要的字符结尾,例如“(001)”、“(014)”、“(013)”等,具有 space、括号和数字,我想删除。此外,header 没有这个问题,我需要所有其他列完好无损,所以这些应该不会受到影响。

enter image description here

我可以在 MS Excel 中使用以下公式

=左(A1,LEN(A1)-6)

(https://www.mrexcel.com/board/threads/how-can-i-remove-the-last-5-characters-from-a-cell.272639/)

但我想在 R 中完成。(PS - 我是 R 的业​​余爱好者)

请帮忙。

我建议看看另一个人的回答post:

How to remove last n characters from every element in the R vector

我根据你的情况改编了@nfmcclure 的解决方案。

#Example dataframe 
df <- structure(list(location = c("Akola (001)", "Jamkhed (014)", "Karjat (013)", 
                                  "Kopargaeon (003)")), class = "data.frame", row.names = c(NA, 
                                                                                            -4L))
#Solution
substr(df$location,1,nchar(df$location)-5)