Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop: replacement has one row more than data

Tags:

for-loop

r

I am an beginner in R and have a problem. Any help would really be appreciated! When I apply the for loop in the following (simplified) case, I get an error message saying "replacement has 5 rows, data has 4"

Country <- c("Germany", "France", "Italy", "Spain")
Unemploy <- c(2, 3, 4, 10)
Growth <- c(2, 7, 6, 9)
data <- data.frame(Country, Unemploy, Growth)

for (i in data$Country) {
     if (identical(data$Country[i], "France")) {
          data$Growth[i] <- "5"
     } else {
          data$Growth[i] <- "2"
     }
}

Following message given out:

Error in `$<-.data.frame`(`*tmp*`, "Growth", value = c("2", "2", "2",  : 
replacement has 5 rows, data has 4
like image 724
user3076270 Avatar asked Dec 06 '13 23:12

user3076270


2 Answers

Use ifelse instead

data[ ,"Growth"] <- ifelse(data[ , "Country"] == "France", "5", "2")
like image 57
Jilber Urbina Avatar answered Nov 08 '22 09:11

Jilber Urbina


Check this out:

> for (i in data$Country){print(i)}
[1] "Germany"
[1] "France"
[1] "Italy"
[1] "Spain"

The i in data$Country syntax iterates through the values in that data.frame attribute. You are then using i as if it is a numerical index. So what you are trying to do is something like this:

for (i in 1:length(data$Country)) {if (identical(data$Country[i],"France"))
+ {data$Growth[i]<-"5"}else{data$Growth[i]<-"2"}}

That being said the above is not idiomatic R, please see @Jilber's answer for a more idiomatic solution.

like image 2
qwwqwwq Avatar answered Nov 08 '22 09:11

qwwqwwq