我的数据类似于:
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 :(得分: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)
希望它有所帮助。
答案 1 :(得分: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" , ]