![](/img/trans.png)
[英]Create new column using grouped column and numeric column from different data frame - R
[英]R - Create column and populate with data grouped from another column
我在R中有一個名為hues的數據框,它有一列稱為color,其中包含多種顏色的行
我正在嘗試創建一個名為colorez的新列,其值將是基於color列中的值的組名
我無法正確使用ifelse來解決問題
hues$colorez <- ifelse(hues$"color == blue,red,purple,black, "primary")
ifelse(hues$"color == yellow, "secondary")
ifelse(hues$"color == pink,orange, "tertiary")
以下是我要創建的
color colorez
blue primary
red primary
yellow secondary
purple primary
pink tertiary
orange tertiary
yellow secondary
red primary
black primary
orange tertiary
yellow secondary
我認為更簡單的方法是使用合並或聯接。 如果您創建第二個數據框, 例如 colors
,如示例中所示, colorez
列為color
和colorez
,則類似:
merge(hues, colors)
應該工作,假設每個hue$color
都在colors$color
。
如果您想保存一些輸入內容,也可以執行以下操作:
hues$colorez <- ifelse(hues$color %in% c("pink", "orange"), "tertiary",
ifelse(hues$color == "yellow", "secondary", "primary"))
假定您除了數據集中提到的顏色外沒有其他顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.