To formalize what someone else used setNames for:
add_row <- function(original_data, new_vals_list){
# appends row to dataset while assuming new vals are ordered and classed appropriately.
# new_vals must be a list not a single vector.
rbind(
original_data,
setNames(data.frame(new_vals_list), colnames(original_data))
)
}
It preserves class when legal and passes errors elsewhere.
m <- mtcars[ ,1:3]
m$cyl <- as.factor(m$cyl)
str(m)
#'data.frame': 32 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Factor preserved when adding 4, even though it was passed as a numeric.
str(add_row(m, list(20,4,160)))
#'data.frame': 33 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Attempting to pass a non- 4,6,8 would return an error that factor level is invalid.
str(add_row(m, list(20,3,160)))
# 'data.frame': 33 obs. of 3 variables:
# $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
# $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
# $ disp: num 160 160 108 258 360 ...
Warning message:
In `[<-.factor`(`*tmp*`, ri, value = 3) :
invalid factor level, NA generated
de
too.names(de) <- c("hello","goodbye")
andrbind
– Khashaarbind(df, setNames(de, names(df)))
– Rich Scrivenrbind(data.frame(a = 1), data.frame(b = 2))
.. why would you want to? I would hope that would throw an error regardless. It's likemerge
'ing with a randomby
variable. And this is 2015, doesn't everyone setoptions(stringsAsFactors = FALSE)
? – rawrstringsAsFactors=FALSE
can be a quick fix, but changing the defaults that other people are going to have set differently can really ruin a day. – thelatemail