[英]Removing all characters after Special Character in Column Name
我有一個導入到R中的數據集,但是需要刪除“(”之后的列名稱中的所有內容。我已經嘗試過string.split(), sub(), and grepl()
函數,但是沒有成功,我們將不勝感激!
我希望以下成為:
水果=>水果
蔬菜(少量)=>蔬菜
面包屑=>面包屑
奶酪(切達干酪)=>奶酪
酸奶(純%)=>酸奶
使用基數R:
items <- c('Fruit', 'Vegetables (Few)', 'Bread Crumbs', 'Cheese (Cheddar)', 'Yogurt (Plain%)')
items_simplified <- trimws(gsub('\\(.*', '', items))
> items_simplified
[1] "Fruit" "Vegetables" "Bread Crumbs" "Cheese" "Yogurt"
你也可以使用stringr
從tidyverse
包:
library(stringr)
items_stringr <- str_trim(str_extract(items, '[^(]*'))
> items_stringr
[1] "Fruit" "Vegetables" "Bread Crumbs" "Cheese" "Yogurt"
trimws
和str_trim
從項目中修剪尾隨和前導空格。
使用正則表達式或正則表達式
像:/(。+)/ g
並刪除找到的所有內容
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.