我有一個包含 27 列的資料框。所有這些列的資料都具有類似于下面的結構。
principal_amt <- c('"pa": "5975.00"', '"pa": "2285.00"', '"pa": "15822.00"')
closed_accounts <- c( '"ca": 0', '"ca": 3', '"ca": 0')
status <- c(' "loan_status": "Paid" ', ' "loan_status": "Funded"',' "loan_status": "Funded"')
DF <- data.frame(principal_amt, closed_accounts)
我想自動洗掉觀察中存在的雙引號,以便最終資料框具有與此類似的結構。
principal_amt <- c(5975.00, 2285.00, 15822.00)
closed_accounts <- c(0, 3, 0)
status <- c('Paid','Funded','Funded')
DF_Final <- data.frame(principal_amt, closed_accounts)
我該怎么做?
uj5u.com熱心網友回復:
該readr軟體包附帶了parse_number針對此類用例的便捷功能。
library(tidyverse)
DF %>%
mutate(across(.fns = parse_number))
principal_amt closed_accounts
1 5975 0
2 2285 3
3 15822 0
更新了名義變數的方法 - 提取匹配項。往后看: ",然后提取所有內容,直到單詞邊緣的空字串。
DF %>%
mutate(across(c(1,3), parse_number),
across(2, str_extract, "(?<=: \").*\\b"))
principal_amt status closed_accounts
1 5975 Paid 0
2 2285 Funded 3
3 15822 Funded 0
uj5u.com熱心網友回復:
這將完成這項作業。
principal_amt <- gsub("[^0-9.-]", "", c('"pa": "5975.00"', '"pa": "2285.00"', '"pa": "15822.00"'))
closed_accounts <- gsub("[^0-9.-]", "",c( '"ca": 0', '"ca": 3', '"ca": 0'))
DF <- data.frame(principal_amt, closed_accounts)
uj5u.com熱心網友回復:
堿基R
DF <- as.data.frame(apply(
apply(DF, 2, gsub, pattern = '[^0-9.-]', replacement = ''), 2, as.numeric
))
輸出
> str(DF)
'data.frame': 3 obs. of 2 variables:
$ principal_amt : num 5975 2285 15822
$ closed_accounts: num 0 3 0
添加(在編輯OP的問題后)
如果在data.frame數字變數旁邊還包含字符變數,則以下內容應該有效。
adapt_df <- \(DF) {
new_df <- as.data.frame(sapply(1:ncol(DF), \(i) {
trimws(gsub(pattern = ifelse(grepl('\\d', DF[, i]), '[^0-9.-]', '^\\s.*\\b.*:|\\s$|"')[i], replacement = '', DF[, i]))
}))
for(i in 1:ncol(DF)) {
new_df[, i] <- ifelse(grepl('\\d', new_df[, i]), as.numeric(new_df[, i]), new_df[, i])
}
names(new_df) <- names(DF)
return(new_df)
}
DF <- adapt_df(DF)
輸出
> str(DF)
'data.frame': 3 obs. of 3 variables:
$ principal_amt : num 5975 2285 15822
$ closed_accounts: num 0 3 0
$ status : chr "Paid" "Funded" "Funded"
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409170.html
標籤:
上一篇:變異子集平均值并添加到所有組R
下一篇:如何計算字串并設定一個數字?
