数据框中的列值中的 gsub

gsub in columns value in dataframe

我有一个包含多列的文件。我正在显示两列我感兴趣的两列

 Probe.Set.ID         Entrez.Gene
A01157cds_s_at               50682
A03913cds_s_at               29366
A04674cds_s_at 24860 /// 100909612
A07543cds_s_at               24867
A09811cds_s_at               25662
----                          ----
A16585cds_s_at               25616

我需要将 /// 替换为“\t”(制表符),输出应该类似于

A01157cds_s_at;50682
A03913cds_s_at;29366
A04674cds_s_at;24860      100909612

此外,我需要避免使用“---”

您似乎想要对数据进行子集化,然后将两列粘贴在一起,然后使用 gsub 替换“///”。这是我想出的, dat 是包含两列的数据框。

dat = dat[dat$Probe.Set.ID != "----",] # removes the rows with "---"
dat = paste0(dat$Probe.Set.ID, ";", dat$Entrez.Gene) # pastes the columns together and adds the ";"
dat = gsub("///","\t",dat) # replaces the "///" with a tab

此外,使用 cat() 查看选项卡而不是“\t”。我从这里得到的:How to replace specific characters of a string with tab in R。这将输出一个列表而不是 data.frame。可以用data.frame()转换回来,但是之后就不能用cat()查看了。

这里是使用 dplyr 的稍微不同的方法:

data <- data.frame(Probe.Set.ID = c("A01157cds_s_at",
                                "A03913cds_s_at",
                                "A04674cds_s_at",
                                "A07543cds_s_at",
                                "A09811cds_s_at",
                                "----",
                                "A16585cds_s_at"),
               Entrez.Gene = c("50682",
                               "29366",
                               "24860 /// 100909612",
                               "24867",
                               "25662",
                               "----",
                               "25616")
)

if(!require(dplyr)) install.packages("dplyr")
library(dplyr)

data %>% 
  filter(Entrez.Gene != "----") %>%
  mutate(new_column = paste(Probe.Set.ID,
                        gsub("///", "\t", Entrez.Gene),
                        sep = ";"
                        )
     ) %>% select(new_column)

我们可以在这里使用dplyrtidyr

library(dplyr)
library(tidyr)

> df <- data.frame(
    col1 = c('A01157cds_s_at', 'A03913cds_s_at', 'A04674cds_s_at', 'A07543cds_s_at', '----'), 
    col2 = c('50682', '29366', '24860 /// 100909612', '24867', '----'))


> df %>% filter(col1 != '----') %>% 
    separate(col2, c('col2_first', 'col2_second'), '///', remove = T) %>%
    unite(col1_new, c(col1, col2_first), sep = ';', remove = T)

> df

##                col1_new col2_second
## 1  A01157cds_s_at;50682        <NA>
## 2  A03913cds_s_at;29366        <NA>
## 3  A04674cds_s_at;24860    100909612
## 4  A07543cds_s_at;24867        <NA>
  • filter 删除带有 col1 == '----' 的观测值。
  • separatecol2 分成两列,即 col2_firstcol2_second
  • unitecol1col2_first; 作为分隔符连接起来。