-2

In Matlab, creating an empty vector that will later be filled looks like this:

v2 = []

How do I do the same in r? I will use this empty vector to fill it when a condition is met. I don't know its future length. For reference, here is my code in r.

dfx <- read.csv("AllDataNewConversions.csv",header = TRUE, sep =",",check.names=FALSE) 
df <- na.omit(dfx) # removes NA 

v2 <- {}
new_val <- {}
for (i in 1:length(df)){ 
  if (df$Texture[i] == 'Silt Loam'){ 
    new_val <- df$`pH 1:1`[i]}
  v2[i] <- new_val
}
Xochilth
  • 1
  • 1
  • 3
  • 2
    Does this answer your question? [How to create an empty R vector to add new items](https://stackoverflow.com/questions/3413879/how-to-create-an-empty-r-vector-to-add-new-items) – fabla Oct 01 '20 at 16:05
  • 2
    You generally *shouldn’t*. Creating an empty vector and appending to it is an anti-pattern because it’s inefficient and unnecessarily verbose. This isn’t just true in R, either: it’s a general principle. – Konrad Rudolph Oct 01 '20 at 16:10
  • I don't think you need a loop here. It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Oct 01 '20 at 16:17

1 Answers1

-2

There are several ways to create empty vector in r. For example,

v2<-NULL

or

v2<-c()

Try this:

v2 <- NULL

for (i in 1:length(df)){ 
if (df$Texture[i] == 'Silt Loam'){ 
  new_val <- df$`pH 1:1`[i]}
v2[i] <- new_val
}
ssaha
  • 459
  • 2
  • 10