2017-04-24 71 views
0

我在R上苦苦掙扎。期待基於來自另一列的字符串創建基於字符串值的新列。我能夠創建一個空列,但我很困惑如何基於具有其他字符串的列創建新字符串。如果第一欄叫做銀行的數據是jpm,cs,gs,bmo等,那麼我想能夠說出北美的所有jpm實例的空列4,並且把瑞士的所有cs實例放在瑞士。感謝您的幫助R - 將字符串放入新的空列中,並根據另一列中的字符串文本

如:

Banks   New column 
JPM    North America 
CS    Switzerland 
JPM    North America 
GS 
CS    Switzerland 
BMO 
CS    Switzerland 
+0

嘗試尋找在R上的'ifelse'命令還有'%在%'運營商。一個簡單的例子可能是:'ifelse(Banks%in%「JPM」,「North America」,「」)' –

+0

也許[this post](http://stackoverflow.com/documentation/r/1088/creating-vectors/10854/created-named-vectors)在SO文檔中描述命名向量將會很有幫助。 – lmo

回答

1

你需要的是有一個映射表,然後用舊data.frame合併。

df <- data.frame(Banks = c("JPM", "CS", "GS"), New_Col = c("North America", "Switzerland", "")) 
res <- merge(df_old, df, by = "Banks", all.x = T) 
+1

或者,添加列,如'df_old $ col < - df $ new [match(df_old $ Banks,df $ Banks)]' – Frank

1

另一種方法是使用case_whendplyr

df <-read.table(text="Banks 
JPM 
CS 
JPM 
GS 
CS 
BMO 
CS",header=TRUE,stringsAsFactors=FALSE) 

library(dplyr) 
df%>% 
mutate(New_column=case_when(
.$Banks %in% c("JPM","BMO","GS") ~ "North America", 
.$Banks %in% c("CS")    ~ "Switzerland" 
)) 

    Banks New_column 
1 JPM North America 
2 CS Switzerland 
3 JPM North America 
4 GS North America 
5 CS Switzerland 
6 BMO North America 
7 CS Switzerland 
+0

不需要使用'.banks',只需'Banks'就可以了mutate()'調用。 –

+0

@StevenBeaupré我剛查過。您的建議適用於dplyr(0.6.0)的開發版本。因爲它在0.5.0中不起作用,所以我會在這一刻離開它。 –

相關問題