2016-01-12 67 views
0

我有一個類似於數據:填充數據下降到下一行

Alabama Age>50 Value1 Value2 Value3 
     Age<50 Value1 Value2 Value3 
Alaska Age>50 Value1 Value2 Value3 
     Age<50 Value1 Value2 Value3 

我只需要保持數據Age<50。我如何重複狀態名稱到它下面的行?我創建了一個狀態名稱的字符串,但我不確定如何將它插入到第一列中的每一行中。

data.frame頭是:

d <- structure(c("ALABAMA", "", "ALASKA", "", "ARIZONA", "", "Under 18", 
     "Total all ages", "Under 18", "Total all ages", "Under 18", "Total all ages", 
     "0", "1", "10", "87", "46", "303", "0", "0", "0", "36", "6", "855", "84,843", 
     "", "469,145", "", "6,303,555", ""), .Dim = c(6L, 5L), .Dimnames = list(NULL, 
     c("State", "", "Rape3", "Prostitution and\ncommercialized\nvice", 
     "2014\nestimated \npopulation"))) 
+0

參見[這裏](http://stackoverflow.com/questions/14843887/in-r-merge-two-data-frames-fill-down-the-blanks)填補空白。試試像這樣過濾'df < - df [df $ age_column =='Age> 50「,]'其中df是一個數據框。 – Mist

+0

你的數據是什麼類型的對象還不是很清楚。你可以發佈'dput(head(yourdata))'的結果嗎? – Molx

+0

結果: 結構(c「ALABAMA」,「」,「ALASKA」,「」,「ARIZONA」,「」,「未滿18歲」, 「所有年齡的人共計」,「未滿18歲」,「總計全部「18歲以下」,「所有年齡的人共計」, 「0」,「1」,「10」,「87」,「46」,「303」,「0」,「0」,「 ,「36」,「6」, 「855」,「84,843」,「」,「469,145」,「」,「6,303,555」,「」),.Dim = c(6L, 5L),.Dimnames = list(NULL,c(「State」,「」,「Rape3」,「Prostitution and \ ncommercialized \ nvice」, 「2014 \ nestimated \ npopulation」))) – Tom

回答

0

假如你有一個列標題年齡

假設你的數據被稱爲MyDataFrame

您可以使用,例如:

# Load required package zoo 
if(library("zoo", logical.return=TRUE, quietly=TRUE, warn.conflicts = FALSE)==FALSE){ 
    install.packages("zoo") 
} else{require("zoo") } 

MyDataFrame$Age<-na.locf(MyDataFrame$Age, na.rm=FALSE) 

希望它有幫助。

+0

這似乎沒有回答這個問題(或者至少是我對它的理解)。 OP想要填寫狀態名稱。 – jbaums

+0

哦,我明白了。您是否從包動物園看na.locf()? –

+0

注意:你可以用'if(!require(zoo))'替換所有'庫'東西。 – jbaums

0

這個怎麼樣:

df <- as.data.frame(structure(c("ALABAMA", "", "ALASKA", "", "ARIZONA", "", "Under 18", "Total all ages", "Under 18", "Total all ages", "Under 18", "Total all ages", "0", "1", "10", "87", "46", "303", "0", "0", "0", "36", "6", "855", "84,843", "", "469,145", "", "6,303,555", ""), .Dim = c(6L, 5L), .Dimnames = list(NULL, c("State", "", "Rape3", "Prostitution and\ncommercialized\nvice", "2014\nestimated \npopulation"))), stringsAsFactors = FALSE) 
names(df)[5] <- "est_pop" 
df$est_pop[df$est_pop == ""] <- NA 
df$State[df$State == ""] <- NA 

library(zoo) 

df$State <- na.locf(df$State,na.rm = TRUE) 
df$est_pop <- na.locf(df$est_pop,na.rm = TRUE) 
df <- df[df$V2 == "Total all ages" , ]