2017-04-09 1 views
0

저는 R 초보자입니다. 그래서 기본적인 질문을 용서해주십시오.R 행 및 열 이름 반복 반복 fory

여기 내 데이터의 .csv에 a Dropbox link이 있습니다.

저는 1990 년부터 2010 년까지의 데이터를 국가별로 가지고 있습니다. 내 데이터가 넓습니다. 각 국가는 행으로, 매년 두 개의 데이터 소스에 해당하는 두 개의 열이 있습니다. 그러나 일부 국가에서는 데이터가 완전하지 않습니다. 예를 들어 한 국가 행에 1990-1995 열에 NA 값이있을 수 있습니다.

두 개의 열을 만들고 각 국가 행에 대해이 열의 값을 두 가지 데이터 형식 각각의 초기 값이 아닌 으로하고 싶습니다.

또 다른 두 개의 열을 만들고 싶습니다. 각 국가 행에 대해이 두 열의 값이 가장 초기 비 -NA 두 데이터 형식 각각으로하고 싶습니다.

그래서 마지막 네 기둥 같은 것입니다 :

여기
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