Home > Enterprise >  how to rename the rows of a column extracted from row names?
how to rename the rows of a column extracted from row names?

Time:10-13

I have added a new column to my data frame by assigning row names as a column, and I have renamed the column "Stations". The problem is that rows of the new column contain character names with a set of numbers representing row numbers, and I want to keep only row names as character names in my new column and delete the set of numbers (row numbers).

Therefore, anyone can help to assign row names as a column by only keeping digits representing row names as characters without row numbers, or renaming all rows in Stations's column by deleting all the last digits representing row numbers.

> colnames(myDF)[1] <- "Stations"
> head(myDF)
                 Stations year month monthly_precip_sum monthly_precip_avg
JPS6306031.1 JPS6306031.1 1998     1               20.5         0.66129032
JPS6306031.2 JPS6306031.2 1999     1              105.0         3.38709677
JPS6306031.3 JPS6306031.3 2000     1               27.7         0.89354839
JPS6306031.4 JPS6306031.4 2001     1              269.6         8.69677419
JPS6306031.5 JPS6306031.5 2002     1                0.0         0.00000000
JPS6306031.6 JPS6306031.6 2003     1                2.4         0.07741935

CodePudding user response:

The question is answered by the respondents of this question Remove last numbers in rows in R

CodePudding user response:

EDIT:

If the aim is to "renam[e] all rows in Stations's column by deleting all the last digits representing row numbers", which the OP explains in comments are those digits occurring after the ., then this should work:

library(dplyr)
df %>%
  mutate(Stations = gsub("(.*?)\\.\\d ", "\\1", Stations))

CodePudding user response:

Assuming all of your Station names are the same length as the example you provided, you could try this (using the stringr package):

myDF$Stations = stringr::str_sub(myDF$Stations, 1, 10)
  • Related