2017-01-12 4 views
1

私はここで解決策を探していて、私が望むものを達成するために複数の方法を試してきましたが、役に立たないです!私は本当にいくつかの助けに感謝します。R:複数のテーブル間で値を変更する

私は異なる国のデータを持ついくつかのテーブルを持っています。私はこれらのテーブルを国ごとにマージする必要がありますが、同じ国ではテーブルごとに異なる言い方をすることが多いので、最初にそれらを標準化する必要があります。

例TABLE1:

birth_country mean_age 
China   37 
Germany   42 

例表2:

birth_country     proportion_male 
Federal Republic of Germany  54 
China, People's Republic of  43 

は、だから私は(私はそれを行う際に、単一のテーブルに対して、次のように動作します)このような何かをしたいです

table1$birth_country[table1$birth_country == "China"] <- "China, People\'s Republic of" 
table1$birth_country[table1$birth_country == "Federal Republic of Germany"] <- "Germany" 

私が試しても、このようなプロセスをすべてのテーブルに適用することはできません。私は、次の少なくとも10件のバリエーション...で、lapplyforループを試してみた:

 standardizeCountryNames<-function(x){ 
      x[x == "China"] <- "China, People\'s Republic of" 
      x[x == "Federal Republic of Germany"] <- "Germany" 
     } 

    tables<-list(table1, table2, table3) 

lapply(tables, function(i) {standardizeCountryNames(i$birth_country)}) 

for (k in 1:length(tables)){ 

      tables[[k]]$birth_country[tables[[k]]$birth_country == "China"] <- "China, People\'s Republic of" } 

私はさまざまな方法でbirth_country変数を参照しようとしました、例えば、with(table)attach(table)を使用します。

ご協力いただければ幸いです! (:

答えて

1

あなたはほとんどがあった:

table1 <- read.table(
    text = "birth_country mean_age 
China   37 
Germany   42", 
    header = TRUE, stringsAsFactors = FALSE) 

table2 <- read.table(
    text = 'birth_country     proportion_male 
"Federal Republic of Germany"  54 
"China, People\'s Republic of"  43', 
    header = TRUE, stringsAsFactors = FALSE) 

standardizeCountryNames<-function(x){ 
    x$birth_country[x$birth_country == "China"] <- "China, People\'s Republic of" 
    x$birth_country[x$birth_country == "Federal Republic of Germany"] <- "Germany" 
    x 
} 

tables<-list(table1, table2) 

lapply(tables, function(i) {standardizeCountryNames(i)}) 
# [[1]] 
#     birth_country mean_age 
# 1 China, People's Republic of  37 
# 2      Germany  42 
# 
# [[2]] 
#     birth_country proportion_male 
# 1      Germany    54 
# 2 China, People's Republic of    43 
+0

は、私はあなたの助けに感謝しかし、私はまだ問題を抱えている!): 私は私の機能をフォーマットし、lapplyすると、あなたの応答で行ったように、出力I取得です: '[[1]] [1] "ガボン共和国" [[2]] [1] "ガボン共和国" [[3]] [1] "ガボン共和国"' (私のfの行の1つ関税は x $ source_country_or_territory [x $ source_country_or_territory == "Gabon"] < - "Gabon Republic" 私のテーブルを見ると、国名は変更されていません。ガボンでさえない – NewR

+0

関数の最後の行は 'x'(または' return(x) 'と等価)でなければなりません。元のテーブルの値は変更されません。 'lapply(...'の結果は 'tables < - lapply(...'または 'whatever_suits_you < - lapply(...' –

+0

@NewR)の影響を受けるはずです。これがあなたの質問に答えたなら、 –

関連する問題