Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

r - NAs are not allowed in subscripted assignments

I have a simple issue, but I couldn't grasp the logic to overcome it.

I have numeric vectors with NAs and want to apply a condition-dependent operation on them.

A simple example similar to my problem is:

x <- c(1,3,5,7,NA,2,4,6)
x[x>=5] <- c(1:8)[x>=5]
x[x<5] <- (c(1:8)*10)[x<5]

It returns the error "NAs are not allowed in subscripted assignments", so I'd like to know what would be a sensible solution for that, given that running each attribution separately works as expected.

I would like to have the expected result of:

[1]  10  20  3  4 NA  60  70  8

Preferably without having to make a for loop, as this operation is already in a function for null modelling with lots of iterations that is taking ages.

Thank you in advance, Leonardo

NB. NAs mean Not Available values

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your logic will need to also exclude NAs in the subset. See the following example. Note the subsets vectors are stored away before x is modified.

x <- c(1,3,5,7,NA,2,4,6)
subset1 <- x>=5 & !is.na(x)
subset2 <-  x<5 & !is.na(x)

x[subset1] <- which(subset1)
x[subset2] <- 10*which(subset2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...