我有一個單列矩陣,其中變數連接在一起以輸入到計算機系統。有些行,但不是全部,有一個我需要提取的數字,減少 5%,然后在字串中替換。我想避免 for 回圈 - 這是lapply一種事情嗎?
鑒于此資料子集:
1989-05-04 [Maize].Sow(cultivar: B_100, population: 6, depth: 50, rowSpacing: 762)
1989-06-26 [Fertiliser].Apply(Amount: 124, Type: NO3N)
1989-10-23 [Maize].Harvest
僅對于其中包含 [Fertiliser] 的行,我需要提取“數量:”后面的數字,在本例中為 124。然后我需要將其乘以 0.95 并替換它。最終結果應該是這樣的:
1989-05-04 [Maize].Sow(cultivar: B_100, population: 6, depth: 50, rowSpacing: 762)
1989-06-26 [Fertiliser].Apply(Amount: 117.8, Type: NO3N)
1989-10-23 [Maize].Harvest
這是一個資料框:
field_ops <- data.frame(V1=c("1989-05-04 [Maize].Sow(cultivar: B_100, population: 6, depth: 50, rowSpacing: 762)","1989-06-26 [Fertiliser].Apply(Amount: 124, Type: NO3N)","1989-10-23 [Maize].Harvest"))
提前感謝您的任何想法。
uj5u.com熱心網友回復:
這是一個使用 的選項tidyverse,我們可以在其中提取 之后的值Amount:,轉換為數字,進行計算,轉換回字符,然后在列中替換具有 的行的值Fertiliser。
library(tidyverse)
field_ops %>%
mutate(x = as.character(as.numeric(str_extract(V1, "(?i)(?<=Amount:\\D)\\d "))*0.95),
V1 = ifelse(str_detect(V1, "Fertiliser"), str_replace(V1,"(?i)(?<=Amount:\\D)\\d ", x), V1)) %>%
select(-x)
輸出
V1
1 1989-05-04 [Maize].Sow(cultivar: B_100, population: 6, depth: 50, rowSpacing: 762)
2 1989-06-26 [Fertiliser].Apply(Amount: 117.8, Type: NO3N)
3 1989-10-23 [Maize].Harvest
或者我們可以只使用stringr:
library(stringr)
str_replace(field_ops$V1,
"(?i)(?<=Amount:\\D)\\d ",
as.character(as.numeric(
str_extract(field_ops$V1, "(?i)(?<=Amount:\\D)\\d ")
) * 0.95))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/525829.html
標籤:r细绳解析代替
上一篇:在bs4中使用find_all
