Reputation: 917
This doesn't work and I'm not sure why.
look_up <- data.frame(flat=c("160","130"),
street=c("stamford%20street", "doddington%20grove"),
city = c("London", "London"),
postcode = c("SE1%20", "se17%20"))
new <- data.frame()
for(i in 1:nrow(look_up)){
new <- rbind(new,look_up$flat[i])
}
Grateful if someone could tell me why please! My result should be a data frame with one column called 'flat' and the values of 160 and 130 on each row. Once I understand this I can move onto the real thing I'm trying to do!
Upvotes: 0
Views: 96
Reputation: 132706
No need for a loop:
look_up[,"flat",drop=FALSE]
As mentioned, the problem with your loop is automatic conversion to factors. You can put options(stringsAsFactors=FALSE)
in front of your script to avoid that.
However, it's almost certain that you are approaching your actual problem in the wrong way. You should probably ask a new question, where you tell us what you actually want to achieve.
Upvotes: 3
Reputation: 6118
You could also do something like:
> look_up <- data.frame(flat=c("160","130"),
+ street=c("stamford%20street", "doddington%20grove"),
+ city = c("London", "London"),
+ postcode = c("SE1%20", "se17%20"))
>
> new <- look_up[,1,drop=FALSE]
> new
flat
1 160
2 130
> class(new)
[1] "data.frame"
This shows your final desired output is a dataframe with 160 and 130 on columns.
If you don't include drop=FALSE
here, then your final output will be a factor.
Hope this helps.
Upvotes: 0
Reputation: 17642
You need to look into the stringsAsFactors
argument of data.frame
.
look_up <- data.frame(flat=c("160","130"),
street=c("stamford%20street", "doddington%20grove"),
city = c("London", "London"),
postcode = c("SE1%20", "se17%20"),
stringsAsFactors = FALSE)
look_up[, "flat", drop = FALSE ]
Upvotes: 0