[英]How do I add a column to a data frame in R based on a partial string in another column?
我正在嘗試根據 R 中另一列中的部分字符串匹配創建一個具有返回值的新列。 第一列是用顏色和 position 表示的籃球隊(例如,yellow_center、red_guard、orange_forward 等)。 我要添加的列是基於顏色的團隊名稱列。 在此示例中,我希望根據行中前面的團隊/位置字符串返回黃色、橙色或紅色值。 我只會使用 4 或 5 個 colors。
我弄亂了 grep、grepl 和轉換函數,但我沒有得到預期的答案。
我試過這個來獲取第一個字母,但它似乎沒有創建列。
轉換(teamfile,team.name <-substr(teamfile$player_position,1)
我已經嘗試了 grepl 幾種方法,但沒有保存它們。
我希望看到的是一個全新的列,其中包含“黃色”或“紅色”或“橙色”,基於 player_position 列值中可能存在的任何顏色。
如果我理解正確,您想從字符串中提取顏色,對嗎? 使用字符串 package 您可以使用
library(stringr)
teamfile$teamname <- str_extract(teamfile$player_position, "^.*(?=\\_)")
# this regex extraxts everything up to a "_"
# so it extracts "orange" based on "orange_guard", "orange_center" or "orange_whatever"
df$new_column = unlist(strsplit(df$colname,'_'))[seq(1,nrow(df),2)]
會將 colors 拆分為自己的列。
這將起作用。 使用 mtcars 作為示例數據集
mtcars$colour<- NA
for( i in c("Merc","Toyota","Ford","Mazda" )) {mtcars[ grepl( i , rownames( mtcars), ) , "colour" ] <- i }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.