1

在合并几个数据集的过程中,我试图删除一个数据帧中对于一个特定变量具有缺失值的所有行(我想暂时将 NA 保留在其他一些列中)。我使用了以下行:

data.frame <- data.frame[!is.na(data.frame$year),]

这成功地删除了所有具有 NA 的行year(并且没有其他行),但是以前有数据的其他列现在完全是 NA。换句话说,非缺失值正在转换为 NA。关于这里发生了什么的任何想法?我尝试了这些替代方案并得到了相同的结果:

data.frame <- subset(data.frame, !is.na(year))

data.frame$x <- ifelse(is.na(data.frame$year) == T, 1, 0);
data.frame <- subset(data.frame, x == 0)

我使用is.na不正确吗?is.na在这种情况下有其他选择吗?任何帮助将不胜感激!

编辑这里是应该重现问题的代码:

#data
tc <- read.csv("http://dl.dropbox.com/u/4115584/tc2008.csv")
frame <- read.csv("http://dl.dropbox.com/u/4115584/frame.csv")

#standardize NA codes
tc[tc == "."] <- NA
tc[tc == -9] <- NA

#standardize spatial units
colnames(frame)[1] <- "loser"
colnames(frame)[2] <- "gainer"
frame$dyad <- paste(frame$loser,frame$gainer,sep="")
tc$dyad <- paste(tc$loser,tc$gainer,sep="")
drops <- c("loser","gainer")
tc <- tc[,!names(tc) %in% drops]
frame <- frame[,!names(frame) %in% drops]
rm(drops)

#merge tc into frame
data <- merge(tc, frame, by.x = "year", by.y = "dyad", all.x=T, all.y=T) #year column is duplicated in       this process. I haven't had this problem with nearly identical code using other data.

rm(tc,frame)

#the first column in the new data frame is the duplicate year, which does not actually contain years.   I'll rename it.
colnames(data)[1] <- "double"

summary(data$year) #shows 833 NA's

summary(data$procedur) #note that at this point there are non-NA values

#later, I want to create 20 year windows following the events in the tc data. For simplicity, I want to remove cases with NA in the year column.

new.data <- data[!is.na(data$year),]

#now let's see what the above operation did
summary(new.data$year) #missing years were successfully removed
summary(new.data$procedur) #this variable is now entirely NA's
4

2 回答 2

2

我认为实际问题出在您的merge.

合并并将数据放入 后data,如果您这样做:

# > table(data$procedur, useNA="always")

#   1      2      3      4      5      6   <NA> 
# 122    112    356     59     39     19 192258 

您会看到 有许多 ( 122+112...+19) 值data$procedur。但是,所有这些值都对应于data$year = NA

> all(is.na(data$year[!is.na(data$procedur)]))
# [1] TRUE # every value of procedur occurs where year = NA

所以,基本上,所有的值procedur也被删除了,因为你删除了那些检查NAin的行year

为了解决这个问题,我认为你应该使用merge

merge(tc, frame, all=T) # it'll automatically calculate common columns
# also this will not result in duplicated year column.

检查此合并是否为您提供所需的结果。

于 2013-02-19T22:29:31.313 回答
0

尝试complete.cases

data.frame.clean <- data.frame[complete.cases(data.frame$year),]

...不过,如上所述,您可能想要选择一个更具描述性的名称。

于 2013-02-19T21:52:13.000 回答