简体   繁体   中英

replacing special characters in first column only in r

Hi I have a text file in this format:

            x  
M.00116    952 
M.00046  41483 
M.00033      4 

I need to replace the "." with an "_" in r. But for I am not able to do it by using this :

sub("\\.", "_", c) 

I get this output

c(952, 41483, 4)

I need an out put like :

x  
M-00116    952 
M-00046  41483 
M-00033      4

What am I doing wrong? Any help is appreciated!

Try:

x <- "M.00116 952 M.00046 41483 M.00033 4"
gsub("\\.", "-", x)

EDIT:

Replace "sub" with gsub :

gsub("\\.", "_", data$colname)

EDIT:

This worked for me:

c <- c("M.00116", "M.00046", "M.00033") 
x <- c("952", "41483", "4")

d <- cbind(c, x)

colnames(d)[2] <- ""

gsub("\\.", "_", d)

     c                
[1,] "M_00116" "952"  
[2,] "M_00046" "41483"
[3,] "M_00033" "4"    

We can use chartr from base R

chartr('.', '-', x)
#[1] "M-00116 952 M-00046 41483 M-00033 4"

data

x <- "M.00116 952 M.00046 41483 M.00033 4"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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