我有以下模式的資料框:tibble [9 x 2] (S3: tbl_df/tbl/data.frame)
$ Date: chr [1:9] "Tuesday 4 October 2022" "Wednesday 5 October 2022" "Thursday 6 October 2022" "Friday 7 October 2022:"
$ SIC : chr [1:9] "01500" "01610" "01629" "01630"
我想使用 grepl 將“SIC”轉換為適當的單詞分類,作為一個名為“Type”的新列。01500 = "混合農業", 01610 = "作物生產支持活動", 01629 = "動物生產支持活動(農場動物寄養和照料除外)nec", 01630 = 收獲后作物活動"
使用 grepl,我已經做到了:
df$Type <- ifelse(grepl("01500", df$SIC), "Mixed farming", "Other")
并且該 ofc 僅適用于一種特定情況。有誰知道如何將其擴展到更多條件?
uj5u.com熱心網友回復:
在這種情況下,命名陣列(字典的 R 等效項)作業得非常好。請注意在名稱上使用引號(這是必要的,因為它們是數字)
dict <- c(
"01500" = "Mixed farming",
"01610" = "Support activities for crop production",
"01629" = "Support activities for animal production (other than farm animal boarding and care) n.e.c.",
"01630" = "Post-harvest crop activities"
)
df$Type <- dict[df$SIC]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515265.html
標籤:r数据框grepl
上一篇:在回圈中創建圖(R)
下一篇:用乘法添加行
