bhbennett3
bhbennett3

Reputation: 123

Why is R Studio telling me that } is unexpected in my For loop?

I am trying to create a simple loop to transform each column of a data frame - which were read into R as factors - to numeric form. My code seems to work fine when transforming an individual column into a percentage, but I can't figure out how to write the for loop.

# Transform data into numeric form
For i in 5:ncol(df){
    vector.i <- as.numeric(sub("%", "", df[,i])) / 100
    next
    }

As you can see, I only want to transform the columns from column 5 on. I am fine with creating the results as individual vectors.

Error: unexpected '}' in "}"

Upvotes: 0

Views: 131

Answers (1)

Henry
Henry

Reputation: 6784

Translating akrun's comment into an answer, R's for-loops and vector names do not work like that, but you could try

for (i in 5:ncol(df)){ 
    assign(paste0("vector.", i), as.numeric(sub("%", "", df[, i])) / 100)
    } 

Upvotes: 2

Related Questions