문제

I'm having some problems to understand the logic of the mistakes I'm getting.

I need to substitute non NA from a data frame with the number 1.

I tested, on a vector -a- , the simple code:

a<-c("a","a","a", NA,"a")
a[!is.na(a)]<-1

And it worked.

But what I need is to apply the same process on a data.frame, imported using:

data<-read.table ("dataframe.csv", header = T, sep = ",",na.strings= c(" ","") )

But when I run the same code as previously written

data$column1[!is.na(data$column1)]<-1

R returns:

Warning message:

In `[<-.factor`(`*tmp*`, !is.na(data$column1), value = c(NA_integer_,  :
  invalid factor level, NA generated

Does someone have any idea where the problem could be?

도움이 되었습니까?

해결책

in the end I was able to do it using the replace function explained in a topic on this forum

data<-replace(data.frame(lapply(data, as.character), stringsAsFactors = FALSE),
    !is.na(data), "1")
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top