1) 我想在 Gnu R 中使用此处的数据集进行子集操作,以便仅包含巴西、时间和所有关于收入份额的系列名称(如"最低 10% 持有的收入份额"、"最低 20% 持有的收入份额"等)。总共将有7个关于收入份额的系列名称。
我尝试了以下命令,但不能子集多个"Series.Name":
test <- melt(subset(WDI, subset = Series.Name == "Income share held by lowest 10%", select = -c(Time.Code, Series.Code, Argentina, Canada, Chile, Colombia, Mexico, USA, Venezuela)), id.vars = c("Series.Name", "Time"))
2)在额外的第二步中,我想删除所有具有NA值的行。
我使用的完整代码如下:
WDI <- read.csv(https://dl.dropboxusercontent.com/u/109495328/WDI_Data_final.csv, na.strings = "..")
library(reshape)
library(reshape2)
WDI <- rename(WDI, (c(Argentina..ARG.="Argentina", Brazil..BRA.="Brazil", Canada..CAN.="Canada", Chile..CHL.="Chile", Colombia..COL.="Colombia", Mexico..MEX.="Mexico", United.States..USA.="USA", Venezuela..RB..VEN.="Venezuela")))
income_brazil_long <- melt(subset(WDI, subset = Series.Name == "Income share held by lowest 10%", select = -c(Time.Code, Series.Code, Argentina, Canada, Chile, Colombia, Mexico, USA, Venezuela)), id.vars = c("Series.Name", "Time"))
查看您的数据,这实际上可能是使用grepl
来帮助子集的最简单方法。
我们使用grepl
在"Series.Name"列中搜索包含字符串"持有的收入份额"的任何行。这将创建一个逻辑向量,指示我们想要的行。我们想要的列是第一列、第三列和第六列。
将其全部包装在 na.omit
中,以删除任何具有NA
值的行。
WDI_Brazil <- na.omit(WDI[grepl("Income share held", WDI$Series.Name),
c(1, 3, 6)])
数据已经"长"了,所以没有必要melt
.data.frame
是什么样子的?
summary(WDI_Brazil)
# Series.Name Time Brazil..BRA.
# Income share held by fourth 20% :28 Min. :1981 Min. : 0.600
# Income share held by highest 10%:28 1st Qu.:1988 1st Qu.: 2.895
# Income share held by highest 20%:28 Median :1996 Median :10.320
# Income share held by lowest 10% :28 Mean :1996 Mean :20.948
# Income share held by lowest 20% :28 3rd Qu.:2004 3rd Qu.:43.797
# Income share held by second 20% :28 Max. :2012 Max. :67.310
# (Other) :28
table(droplevels(WDI_Brazil$Series.Name))
#
# Income share held by fourth 20% Income share held by highest 10% Income share held by highest 20%
# 28 28 28
# Income share held by lowest 10% Income share held by lowest 20% Income share held by second 20%
# 28 28 28
# Income share held by third 20%
# 28
请注意,正如预期的那样,"Series.Name"中有七个因子水平。
好吧,您可以使用base
函数完成所需的操作。
WDI <- read.csv("WDI_Data_final.csv", header=T, na.strings="..")
# The colnames are strange from the file so reset for clarity
colnames(WDI) <- c("Series.Name", "Series.Code", "Time","Time.Code","Argentina",
"Brazil", "Canada", "Chile", "Colombia","Mexico",
"USA", "Venezuela")
# do the subsetting
test <- with(WDI,
WDI[Series.Name=="Income share held by lowest 10%",
c("Brazil","Time", "Series.Name")])
# if you want more, use %in% and specify the Series.Names you care about
test <- with(WDI,
WDI[Series.Name %in% c("Income share held by lowest 10%",
"Income share held by lowest 20%"),
c("Brazil","Time", "Series.Name")])
# if you want all the 'income shares', the grepl solution above by
# Ananda is the most concise.
# you can then use reshape2::melt
melted_test <- melt(test, id.vars=c("Series.Name", "Time"))
要删除NA
只需使用complete.cases
test[complete.cases(test),]