2016-08-08 17 views
0

文をマージデータ。私はベースに共通する3つの異なる領域。これらのデータセットのための7つの異なる年& 7つの他のデータセットは量が挙げられるベース& 1つのデータセット、領域&年を持っ

ただし、7つのデータセットを1つずつベースデータセットにマージする必要があります。どのように達成できますか?

基本データセット:

company_region raised_amount_usd Year 
SF Bay Area 1000050 2011 
SF Bay Area 2520000 2011 
SF Bay Area 15000 2010 
Singapore 615000 2011 

2007年度:

raised_amount_usd z e Year company_region 
1.00E+06 5 0   2007 Singapore 
8.00E+06 6 1   2007 Singapore 

50000 3 0 2007シンガポール 35000 3 0 2007シンガポール

&は、同様に、私は他の年の2008年のデータを持っています-2012.カラムZ &がベースデータセットに必要です。7マージステートメントの作成に代わって、どのようにドンできますか関数を介して?

誰かが助けることができれば素晴らしいだろう。事前に感謝!

答えて

0

あなたは列ZおよびEを維持したい場合は、bind_rows()dplyrパッケージからの回答のようです(ここもCombine two data frames by rows (rbind) when they have different sets of columnsを参照してください)

# Create example 
a <- c(rep("SF Bay Area",3),"Singapore") 
b <- c(1000050,2520000,15000,615000) 
c <- c(2011,2010,2011,2011) 
base <- cbind.data.frame(a,b,c,stringsAsFactors =F) 
colnames(base) <- c("company_region","raised_amount_usd","Year") 


a <- c(rep("Germany",4)) 
b <- c(100055,2524400,150020,68880) 
c <- c(2007,2007,2007,2007) 
e <- c(1,1,1,1) 
z <- c(1,1,1,1) 
data_germany <- cbind.data.frame(a,b,c,e,z,stringsAsFactors =F) 
colnames(data_germany) <- c("company_region","raised_amount_usd","Year","e","z") 

a <- c(rep("Italy",4)) 
b <- c(100055,2524400,150020,68880) 
c <- c(2007,2007,2007,2007) 
e <- c(1,1,1,1) 
z <- c(1,1,1,1) 
data_italy <- cbind.data.frame(a,b,c,e,z,stringsAsFactors =F) 
colnames(data_italy) <- c("company_region","raised_amount_usd","Year","e","z") 

# bin german and italian data at once with dplyr 
library(dplyr) 
base %>% 
    bind_rows(data_germany) %>% 
    bind_rows(data_italy) -> base 

あなたは、z保持しない場合とあなたは次のようなことができます:

# Function to extent base dataframe 
# base_df = base dataframe to extent 
# add_df = dataframe that should be added to the base dataframe 
fun_extent_data <- function(base_df,add_df) { 

    library(dplyr) 
    base_df <- base_df 
    add_df <- add_df 

    # Choose all necessary columns 
    add_df %>% 
    select(company_region,raised_amount_usd,Year) -> add_df_light 

    # Bind the data to the base dataframe 
    rbind.data.frame(base_df,add_df_light,stringsAsFactors = FALSE) -> base_df 

    return(base_df) 
} 

# Use function 
fun_extent_data(base,data_germany) -> base 

# Use function for german and italian data at once with dplyr 
library(dplyr) 
base %>% 
    fun_extent_data(.,data_germany) %>% 
    fun_extent_data(.,data_italy) -> base 
関連する問題