簡體   English   中英

查找字符串中的特定字符,將其刪除,將其余字符轉為數字並除以5

[英]Find specific character in a string, remove it, turn the rest of the characters to number and divide by 5

我正在使用R中的數據框。它有大約18列,其中有數字。 某些單元格帶有“ P”,后跟數字。 對於這些情況,我想刪除“ P”,將其余字符轉換為數字,然后采用該數字除以5。

    > Replace<-data.frame(group=c("P4", "25", "4", "P1", "25"))
    > Replace
    group
    1    P4
    2    25
    3     4
    4    P1
    5    25
    > 

例如,在“替換”中,我希望“ P4”為“ 0.8”,“ P1”為“ 0.2”。 但是“ 25”,“ 4”和“ 25”應保持不變。 謝謝您的幫助!

library(dplyr)
Replace <- mutate(Replace, group = ifelse(grepl("P", group),
                  as.numeric(gsub("P", "", group))/5, as.character(group)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM