2017-04-09 3 views
0

私はRの初心者ですので、基本的な質問をご容赦ください。Rは、行と列の名前を繰り返しループするために入れ子になっています

私のデータの.csvにはa Dropbox linkがあります。

私は1990年から2010年のデータを国ごとに持っています。私のデータは幅が広い:各国は行で、毎年2つのデータソースに対応する2つの列があります。ただし、一部の国ではデータが完全ではありません。たとえば、ある国の行は1990-1995の列にNA値を持つことがあります。

2つの列を作成したいと思います。それぞれの国の行について、これらの列の値が、2つのデータ型のそれぞれの最初の非NA になるようにしたいと思います。

また、2つの他の列を作成したいと思います。各国の行については、これらの列の値を、2つのデータ型のそれぞれの最初の非NA にしたいと思います。

だから、最後の4つの列は以下のようになります。

ここ
1990, 12, 1990, 87 
1990, 7, 1990, 132 
1996, 22, 1996, 173 
1994, 14, 1994, 124 

ようになり、私はループの入れ子のを想像して何で私のラフ半疑似コードの試みです:

for i in (number of rows){ 
    for j in names(df){ 
    if(is.na(df$j) == FALSE) df$earliest_year = j 
    } 
} 

方法は、これらの望ましい4列を生成できますか?ありがとう!

答えて

2

あなたはforループについて言及しました。だから私はforループを作ろうとしました。しかし、後で適用するような他のR関数を試してみてください。

# read data; i'm assuming the first column is row name and not important 
df <- read.csv("wb_wide.csv", row.names = 1) 

# get names of columns for the two datasource 
# here I used grep to find columns names using NY and SP pattern; 
# but if the format is consistentto be alternating, 
# you can use sequence of number 
dataSourceA <- names(df)[grep(x = names(df), pattern = "NY")] 
dataSourceB <- names(df)[grep(x = names(df), pattern = "SP")] 

# create new columns for the data set 
# if i understand it correctly, first non-NA data from source 1 
# and source 2; and then the year of these non-NAs 
df$sourceA <- vector(length = nrow(df)) 
df$yearA <- vector(length = nrow(df)) 
df$sourceB <- vector(length = nrow(df)) 
df$yearB <- vector(length = nrow(df)) 

# start for loop that will iterate per row 
for(i in 1:nrow(df)){ 

    # this is a bit nasty; but the point here is to first select columns for source A 
    # then determine non-NAs, after which select the first and store it in the sourceA column 
    df$sourceA[i] <- df[i, dataSourceA][which(!is.na(df[i , dataSourceA]))[1]] 

    # another nasty one; but I used gsub to clean the column name so that the year will be left 
    # you can also skip this and then just clean afterward 
    df$yearA[i] <- gsub(x = names(df[i, dataSourceA][which(!is.na(df[i , dataSourceA]))[1]]), 
       pattern = "^.*X", replacement = "") 

    # same with the first bit of code, but here selecting from source B 
    df$sourceB[i] <- df[i, dataSourceB][which(!is.na(df[i , dataSourceB]))[1]] 

    # same with the second bit for source B 
    df$yearB[i] <- gsub(x = names(df[i, dataSourceB][which(!is.na(df[i , dataSourceB]))[1]]), 
       pattern = "^.*X", replacement = "") 

} 

私はあなたの例にコードを特定するためにしようとした出力を望んでいた:このコードは、これがあなたの役に立てば幸い、少し長いです。

+0

これは素晴らしいです!どうもありがとうございます!!非常に参考になる説明もあります。 – Jim

関連する問題